通过XMLHttpRequest上传时使用getimagesize()

时间:2012-10-11 08:11:08

标签: php file-upload xmlhttprequest

我正在使用this file uploader并决定验证上传文件的实际内容,以确保它确实是一张图片。所以我想使用带有文件名的PHP getimagesize()函数。 但是没有$_FILES['xxx']['tmp_name']因此我将其传递给getimagesize函数。您建议在我的上传过程中验证实际内容类型是什么?

/**
 * Handle file uploads via XMLHttpRequest
 */
class qqUploadedFileXhr {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);

        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);

        return true;
    }
    function getName() {
        return $_GET['qqfile'];
    }
    function getImageInfo() {
        return getimagesize($_GET['qqfile']); /* no such file or directory */
    }
}

更新

if ($this->file->save($uploadDirectory . $filename . $ext)){
    // if only images are allowed to upload
    if ($imgOnly)
    {
            // get image size and if $imgInfo were false delete uploaded file
        $imgInfo = getimagesize($uploadDirectory . $filename . $ext);
        if (!$imgInfo)
        {
            unlink($uploadDirectory . $filename . $ext);
            return array('error' => 'The file uploaded is not actual image file.');
        }
    }
    return array('success'=>true);
} else {
    return array('error'=> 'Could not save uploaded file.' .
        'The upload was cancelled, or server error encountered');
}

1 个答案:

答案 0 :(得分:1)

函数save接受一个字符串参数,并将上传的图像保存到具有该路径的文件中。所以只需打开传递给save()的文件名。