0

I am downloading the image from URL using file_get_contents function. But in some case I get the error like this

"file_get_contents(http://www.aaaaa.com/multimedia/dynamic/02456/RK_2456652g.jpg): failed to open stream: HTTP request failed!". Only for some of the URL am getting this error, other images are easily downloaded using this code.

I am getting this error when I run this code in cron. But when I manually downloading the image from same URL its downloading. Can anyone please help me to solve this problem.

My code is

 $arr="http://www.aaaa.com/multimedia/dynamic/02077/saibaba_jpg_2077721g.jpg";
 $file = basename($arr); 
 $date = date('Ymd');
 $id=2225;
 if (!file_exists('../media/'.$date)) {
 $path=mkdir('../media/'.$date, 0777, true);
}
 if (!file_exists('../media/'.$date.'/'.$id)) {
 $path=mkdir('../media/'.$date.'/'.$id, 0777, true);
}

//Get the file
$content= file_get_contents($arr);

//Store in the filesystem.
$fp = fopen('../media/'.$date.'/'.$id.'/'.$file, "w");


 fwrite($fp, $content);
 fclose($fp);
CGN
  • 13
  • 4

1 Answers1

0

If you are execute your function then you must provide full path to of your file.LIKE

$arr="http://www.aaaa.com/multimedia/dynamic/02077/saibaba_jpg_2077721g.jpg";
 $file = basename($arr); 
 $date = date('Ymd');
 $id=2225;
 if (!file_exists('/var/www/path_to_Your_folder/media/'.$date)) {
 $path=mkdir('/var/www/path_to_Your_folder/media/'.$date, 0777, true);
}
 if (!file_exists('/var/www/path_to_Your_folder/media/'.$date.'/'.$id)) {
 $path=mkdir('/var/www/path_to_Your_folder/media/'.$date.'/'.$id, 0777, true);
}

//Get the file
$content= file_get_contents($arr);

//Store in the filesystem.
$fp = fopen('/var/www/path_to_Your_folder/media/'.$date.'/'.$id.'/'.$file, "w");


 fwrite($fp, $content);
 fclose($fp)
  • There is no path issue. All the images are downloaded in the given path, its working fine. But I didn’t understand why this error comes only for some URL. Is there any time limitation for file_get_content function? – CGN Jul 01 '15 at 06:29
  • Okay. then you have check for file exist or not. put condition like this if (@'../media/'.$date.'/'.$id.'/'.$file !== false) { $path=mkdir('/var/www/path_to_Your_folder/media/'.$date, 0777, true); } and same for others. –  Jul 01 '15 at 06:37