php file_get_contents function saves invalid image file in my new webserver
-
07-07-2021 - |
Question
I have developed a wordpress plugin which uses file_get_contents()
to retrieve images from distant url and save it in the local folder using fwrite function. The image file gets saved in a local folder so it can be referenced later.
This works fine in one webserver 1. But when I installed the plugin in wordpress maintained in a different new webserver 2, the file gets created in the local folder but seems it gets corrupted. The file is created properly for images which are less than 100kb i guess, but larger files which are properly created in the former webserver 1 are corrupted when retrieved and created in server 2.
Below is the code I use to retrieve images and save to local folder:
//$imgurl = url of the image file and $upload_path
// is path where image will be stored
$file = file_get_contents($imgurl) or die('File too large or inacessible');
$myFile = $upload_path . "\internal\folder\structure\\" . $file_name;
$fh = fopen($myFile, 'w') or die("Error");
$fwrite = fwrite($fh, $file);
if($fwrite === false)
{
echo "error";
}
else
{
echo "file has been created ".$file_name;
}
fclose($fh);
In server 1 this works fine, but in server 2, the file gets created but cant open it because it is corrupted. I guess this probably should have to do with the php configuration of the server 2 but I am not very sure so I am looking forward for your help.
Solution
There could be several reasons
PHP Error generated by something on server2
some output like newline or space before your function
read http://php.net/manual/en/function.file-get-contents.php for hint