使用php:// input和file_put_contents

时间:2022-09-29 13:23:29

I'm receiving files (images) uploaded with Ajax into my PHP script and have got it to work using this:

我正在接收使用Ajax上传的文件(图像)到我的PHP脚本中并使用它来使用它:

$input = fopen("php://input", "r");
file_put_contents('image.jpg', $input);

Obviously I will sanitize input before this operation.

显然我会在此操作之前清理输入。

One thing I wanted to check was the file size prior to creating the new file, as follows:

我想检查的一件事是在创建新文件之前的文件大小,如下所示:

$input = fopen("php://input", "r");
$temp = tmpfile();
$realsize = stream_copy_to_stream($input, $temp);
if ($realsize === $_SERVER["CONTENT_LENGTH"]) {
  file_put_contents('image.jpg', $temp);
}

And that doesn't work. The file is created, but it has a size of 0 bytes, so the content isn't being put into the file. I'm not awfully familiar with using streams, but I don't see why that shouldn't work, so I'm turning to you for help. Thanks in advance!

这不起作用。文件已创建,但其大小为0字节,因此内容未放入文件中。我对使用溪流并不是很熟悉,但我不明白为什么不应该这样做,所以我转向你寻求帮助。提前致谢!

2 个解决方案

#1


4  

The solution was deceptively simple:

解决方案看似简单:

$input = fopen("php://input", "r");
file_put_contents($path, $input);

#2


1  

You are using file resources as if they were strings. Instead you could again use stream_copy_to_stream:

您正在使用文件资源,就像它们是字符串一样。相反,您可以再次使用stream_copy_to_stream:

stream_copy_to_stream($temp, fopen('image.jpg', 'w'));

#1


4  

The solution was deceptively simple:

解决方案看似简单:

$input = fopen("php://input", "r");
file_put_contents($path, $input);

#2


1  

You are using file resources as if they were strings. Instead you could again use stream_copy_to_stream:

您正在使用文件资源,就像它们是字符串一样。相反,您可以再次使用stream_copy_to_stream:

stream_copy_to_stream($temp, fopen('image.jpg', 'w'));