使用php:// input和file_put_contents

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

$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!

The solution was deceptively simple:

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

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

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