php - 流上的 getimagesize() 而不是字符串

标签 php ajax file file-upload inputstream

我正在使用 Valum's file uploader使用 AJAX 上传图像。这个脚本以我不完全理解的方式将文件提交到我的服务器,所以最好通过显示我的服务器端代码来解释:

$pathToFile = $path . $filename;

//Here I get a file not found error, because the file is not yet at this address
getimagesize($pathToFile);

$input = fopen('php://input', 'r');
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);

//Here I get a string expected, resource given error 
getimagesize($input);

fclose($input);

$target = fopen($pathToFile, 'w');
fseek($temp, 0, SEEK_SET);

//Here I get a file not found error, because the image is not at the $target yet
getimagesize($pathToFile);

stream_copy_to_stream($temp, $target);
fclose($target);

//Here it works, because the image is at the desired location so I'm able to access it with $pathToFile. However, the (potentially) malicious file is already in my server.
getimagesize($pathToFile);

问题是我想在这里使用 getimagesize() 执行一些文件验证。 getimagesize 只支持一个字符串,而我只有可用的资源,导致错误:getimagesize expects a string, resource given.

当我在脚本末尾执行 getimagesize($pathTofile) 时它确实有效,但是图像已经上传并且损坏可能已经完成。这样做并在之后执行检查,然后可能删除 te 文件对我来说似乎是不好的做法。

$_REQUEST 中唯一的东西是文件名,我将其用于 var $pathToFile。 $_FILES 为空。

如何对流执行文件验证?

编辑: 解决方法是先将文件放在一个临时目录下,在复制到目标目录之前对临时文件进行校验。

// Store the file in tmp dir, to validate it before storing it in destination dir
$input = fopen('php://input', 'r');
$tmpPath = tempnam(sys_get_temp_dir(), 'upl'); // upl is 3-letter prefix for upload
$tmpStream = fopen($tmpPath, 'w'); // For writing it to tmp dir
stream_copy_to_stream($input, $tmpStream);
fclose($input);
fclose($tmpStream);

// Store the file in destination dir, after validation
$pathToFile = $path . $filename;
$destination = fopen($pathToFile, 'w');
$tmpStream = fopen($tmpPath, 'r'); // For reading it from tmp dir
stream_copy_to_stream($tmpStream, $destination);
fclose($destination);
fclose($tmpStream);

最佳答案

PHP 5.4 现在支持 getimagesizefromstring

查看文档: http://php.net/manual/pt_BR/function.getimagesizefromstring.php

你可以试试:

$input = fopen('php://input', 'r');
$string = stream_get_contents($input);
fclose($input);

getimagesizefromstring($string);

关于php - 流上的 getimagesize() 而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8209646/

相关文章:

python - 在 Django 中保存多张图像时出现问题

php - 有没有办法增加 xdebug 配置文件调用树深度?

上传前 PHP 检查文件大小 - 10 字节

php - 如何选择属于当月的记录

php - 使用 Android Volley 将数组发布到 PHP

jquery - 单击按钮的类中的回显数据

javascript - 根据用户类型进行 Ajax 搜索

java - Java 获取有关已更改文件的信息

c - FILE* 返回初始化变量并插入 FILE* 读取的输出

java - 如何使用servlet将pdf文件存储在postgresql数据库中?