CakePhp,如何添加以检查上传的文件是否仅为图像?

时间:2015-03-28 10:41:26

标签: php validation cakephp mime-types fileinfo

一直试图在旧的书面程序中添加一些代码,我没有写,因为我不知道这段代码有多好用。 以下代码在两个具有不同形式的不同页面中起作用。

$type = $this->data['Gallery']['type'];

if (!empty($this->data)) {
    if (!isset($this->data['Gallery']['gallery_category_id'])) {
        if ($this->data['Gallery']['type'] == 1) {
            echo "<script>alert('" . INFOGALLERYSECTION . "')</script>";
        } elseif ($this->data['Gallery']['type'] == 2) {
            echo "<script>alert('" . INFOSHROTSECTION . "')</script>";
        } else {
        }
    } else {
        // set the upload destination folder
        //$destination = realpath('../../app/webroot/img/gallery') . '/';

        $bigimg = WWW_ROOT . 'img/gallery/big/';
        $smallimg = WWW_ROOT . 'img/gallery/small/';

        // grab the file
        $file = $this->data['Gallery']['photofile'];
        $imageTypes = array("image/gif", "image/jpeg", "image/png"); //List of accepted file extensions. 
        foreach ($iamgeTypes as $type) {                 //check if image type fits one of allowed types
            if ($type == $this->data['type']) {
                // upload the image using the upload component
                $result = $this->Upload->upload($file, $bigimg, null, array('type' => 'resize', 'size' => '965', 'output' => 'jpg'));
                $result = $this->Upload->upload($file, $smallimg, null, array('type' => 'resize', 'size' => '146', 'output' => 'jpg'));
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您需要获取mime类型的上传文件。根据您的PHP版本,有两种方法可以执行此操作。

PHP 5.3&gt; =,PECL fileinfo&gt; = 0.1.0

$file = $this->data['Gallery']['photofile'];
$imageTypes = array("image/gif", "image/jpeg", "image/png"); //List of accepted file extensions.
// get file mime type
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$fileType = finfo_file($fileInfo, $file);
finfo_close($fileInfo);

if (in_array($fileType, $imageTypes)) {
    $result = $this->Upload->upload($file, $bigimg, null, array('type' => 'resize', 'size' => '965', 'output' => 'jpg'));
    $result = $this->Upload->upload($file, $smallimg, null, array('type' => 'resize', 'size' => '146', 'output' => 'jpg'));
}

有关fileinfo功能的更多信息,请参阅documentation

PHP 5.3&lt;

// get file mime type
$fileType = mime_content_type($file);

Documentation mime_content_type()函数。

我不知道你的模型是怎样的,但是在验证器中移动检查mime类型是一种很好的方法。

答案 1 :(得分:0)

$file = $this->data["Gallery"]['photofile'];
if(!empty($file['tmp_name']))
{
    $type = explode('/', $file['type']);
    if($type[0] == 'image')
    {
     // Your Code
    }
}