Morning all,
Theres a few questions around this but none that really answer my question, as far as I ca understand. Basically I have a GD script that deals with resizing and caching images on our server, but I need to do the same with images stored on a remote server.
So, I'm wanting to save the image locally, then resize and display it as normal.
I've got this 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);
This creates the image file, but does not copy it accross? Am I mis开发者_StackOverflow社区sing the point?
Cheers guys.
More simple, you can use the 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 in just 2 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));
Well, I sorted it! After examing my images rather than my code a little closer, it turned out some of the images were erroring on their side, rather than mine. Once I selected an image that worked, my code worked too!
Cheers as always though guys :)
Personally i don't like to use curl functions that write into a file. Try this 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 more simple 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);
精彩评论