gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:09:50 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com