Saving remote image with cURL?

Morning everything

There are several questions about this, but no one answers my question, as far as I understand. Basically, I have a GD script that resizes and caches images on our server, but I need to do the same with images stored on a remote server.

So, I want to save the image locally, then resize and display it as usual.

I have it far ...

$file_name_array = explode('/', $filename); $file_name_array_r = array_reverse($file_name_array); $save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0]; $ch = curl_init($filename); $fp = fopen($save_to, "wb"); // set URL and other appropriate options $options = array(CURLOPT_FILE => $fp, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough) curl_setopt_array($ch, $options); curl_exec($ch); curl_close($ch); fclose($fp); 

Creates an image file but doesn't copy it on top? Am I missing a point?

Greetings guys.

+4
source share
3 answers

Ok, I made it out! After studying my images, and not my code a little closer, it turned out that some of the images were errors on their side, not mine. When I selected an image that worked, my code works too!

Greetings, as always, guys :)

+2
source

More simply, you can use file_put_contents instead of fwrite:

 $file_name_array = explode('/', $filename); $file_name_array_r = array_reverse($file_name_array); $save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0]; file_put_contents($save_to, file_get_contents($filename)); 

or just two lines :)

 $file_name_array_r = array_reverse( explode('/', $filename) ); file_put_contents('system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0], file_get_contents($filename)); 
+3
source

Personally, I do not like to use curl functions that are written to a file. Try instead:

  $file_name_array = explode('/', $filename); $file_name_array_r = array_reverse($file_name_array); $save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0]; $ch = curl_init($filename); $fp = fopen($save_to, "wb"); // set URL and other appropriate options $options = array(CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 60, CURLOPT_RETURNTRANSFER, true //Return transfer result ); curl_setopt_array($ch, $options); //Get the result of the request and write it into the file $res=curl_exec($ch); curl_close($ch); fwrite($fp,$res); fclose($fp); 

But you can use something simpler without curl:

 $file_name_array = explode('/', $filename); $file_name_array_r = array_reverse($file_name_array); $save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0]; $content=file_get_contents($filename); $fp = fopen($save_to, "wb"); fwrite($fp,$content); fclose($fp); 
0
source

Source: https://habr.com/ru/post/1310092/


All Articles