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


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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

You need to login to post a comment.