使用PHP从远程服务器获取并保存/缓存图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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");

以上是关于使用PHP从远程服务器获取并保存/缓存图像的主要内容,如果未能解决你的问题,请参考以下文章