I have faced memory limit problem while reading and outputting an image file. What I do is - check if file exists and if not I get the file from a remote repository, save it and then output it. The question is how do I output the file contents and skip getting the file into memory?
$file = 'someimagefile.jpg';
if(file_exists($file)){
exit(file_get_contents($file));
}
else{
$fileContents = file_get_contents('http://somedomain.com/files/'.$file);
$handle = fopen($file, 'w+');
fwrite($handle, fileContents);
fclose($handle);
exit($fileContents);
}
As far as I understand the exit(file_get_contents($file))
gets the file into memory. I know there is a way to stream a file, but I am not aware of the function mechanics. Will this code do the same thing without using the memory?:
if (file_exists($file)) {
$file = fopen($file, 'r');
exit(stream_get_contents($file));
}
else{
$file = fopen('http://somedomain.com/files/'.$file, 'r');
$dest = fopen($file, 'w+');
stream_copy_to_stream ( $file , $dest );
fclose($file);
fclose($dest);
}