我正在使用Valum的文件上传程序来通过AJAX上传图像。此脚本以我不完全了解的方式将文件提交到我的服务器,因此最好通过展示我的服务器端代码来解释:
问题在于我想要使用getimagesize()进行文件验证,但是getimagesize仅支持字符串,而我只有资源可用,这会导致错误:getimagesize期望一个字符串,但是实际传入的是资源。
当我在脚本末尾执行getimagesize($pathTofile)时,它确实可以工作,但是图像已经被上传,损坏可能已经发生。这样做并随后执行检查,然后也许删除文件似乎不是好的做法。 $_REQUEST中唯一的东西是文件名,我将其用于变量$pathToFile。$_FILES为空。
如何对流执行文件验证?
编辑: 解决方法是先将文件放入临时目录,在将其复制到目标目录之前对临时文件进行验证。
$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期望一个字符串,但是实际传入的是资源。
当我在脚本末尾执行getimagesize($pathTofile)时,它确实可以工作,但是图像已经被上传,损坏可能已经发生。这样做并随后执行检查,然后也许删除文件似乎不是好的做法。 $_REQUEST中唯一的东西是文件名,我将其用于变量$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);