tags:

views:

25

answers:

2

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!

A: 

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'));
nikic
Thanks for your suggestion, but I just gave that a go and it doesn't work.
Rafael
The error was: Warning: file_get_contents() expects parameter 1 to be string, resource given.
Rafael
@Rafael: I edited my answer ;)
nikic
Thanks, that works - but only if you do `fseek($temp, 0, SEEK_SET);` first. So I guess it works, but not with file_put_contents - I'm still interested in knowing why in my original post the first bit of code works, but not after creating the temp file. In other words, I still want to know how to do this with file_put_contents. :)
Rafael
@Rafael: file_put_contents expects a file *name*. tempfile gives a file *resource*. If you want to get a temporary file name, use tempnam.
nikic
A: 

The solution was deceptively simple:

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