3

Advise me the most optimal way to save large files from php stdin, please. iOS developer sends me large video content to server and i have to store it in to files.

I read the stdin thread with video data and write it to the file. For example, in this way:

$handle = fopen("php://input", "rb");    
while (!feof($handle)) {
      $http_raw_post_data .= fread($handle, 8192);
}

What function is better to use? file_get_contents or fread or something else?

Andrei Nikolaev
  • 113
  • 2
  • 13
  • 4
    If you can influence the upload process I would suggest to send it as multipart form data. It would be available via $_FILES this way and the web server itself would handle the upload of the file and save it to filesystem. expecting this the most performant way. – hek2mgl Jan 06 '13 at 23:41
  • hek2mgl, thanks for your answer. In future we'll try to remake uploading proccess with mime functionality, but now we are wanting to do it this way. – Andrei Nikolaev Jan 06 '13 at 23:49

3 Answers3

4

I agree with @hek2mgl that treating this as a multipart form upload would make most sense, but if you can't alter your input interface then you can use file_put_contents() on a stream instead of looping through the file yourself.

$handle = fopen("php://input", "rb");  
if (false === file_put_contents("outputfile.dat", $handle))
{
  // handle error
}
fclose($handle);

It's cleaner than iterating through the file, and it might be faster (I haven't tested).

John Carter
  • 53,924
  • 26
  • 111
  • 144
2

Don't use file_get_contents because it would attempt to load all the content of the file into a string

FROM PHP DOC

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Am sure you just want to create the movie file on your server .. this is a more efficient way

$in = fopen("php://input", "rb");
$out = fopen('largefile.dat', 'w');

while ( ! feof($in) ) {
    fwrite($out, fread($in, 8192));
}
Baba
  • 94,024
  • 28
  • 166
  • 217
0

If you use nginx as web server i want to recommend nginx upload module with possibility to resume upload.

Andrei Nikolaev
  • 113
  • 2
  • 13