Posted By

adamcoulombe on 10/06/09


Tagged

url fetch php image remote save cache


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

riddla
weavermedia
Priestd09


Fetch & Save / Cache an image from a remote server using PHP


 / Published in: PHP
 

  1. function cache_image($image_url){
  2. //replace with your cache directory
  3. $image_path = 'path/to/cache/dir/';
  4. //get the name of the file
  5. $exploded_image_url = explode("/",$image_url);
  6. $image_filename = end($exploded_image_url);
  7. $exploded_image_filename = explode(".",$image_filename);
  8. $extension = end($exploded_image_filename);
  9. //make sure its an image
  10. if($extension=="gif"||$extension=="jpg"||$extension=="png"){
  11. //get the remote image
  12. $image_to_fetch = file_get_contents($image_url);
  13. //save it
  14. $local_image_file = fopen($image_path.$image_filename, 'w+');
  15. chmod($image_path.$image_filename,0755);
  16. fwrite($local_image_file, $image_to_fetch);
  17. fclose($local_image_file);
  18. }
  19. }
  20.  
  21. //usage
  22. //cache_image("http://www.flickr.com/someimage.jpg");

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Simon on October 7, 2009

Good piece of code. As an addition I would add a strtolower for the extension, so the comparision is the same no matter if the extension is PNG, pNg, PnG or png. Also you could overwrite two images, say you get "domain1.com/test.jpg"and then "someotherdomain.com/test.jpg" the test.jpg would be overwritten. Alternative, you could save it with a has of the url, making it easy to handle. Like make an sha hash out of the image_url variable and save the image under that name. If you need it again, you can search the same way for it and never overwrite it again.

You need to login to post a comment.