Image Cache with cURL and fopen

AddThis Social Bookmark Button

Image Caching Function Script with cURL

I am building a website that pulls images from another website and needs to cache them locally. I needed a script that will allow me to reference an image living on an external website via a function that will cache the image locally and rewrite the image source to my local cached folder. I want to do this by just referencing a an external image source via a simple php function. To clarify, I want to say

<img src=”http://www.flickr.com/image.jpg”>

and have the php function pull the image, cache it in my local directory, and then insert the correct source when it renders the page:

<img src=”/cache/image.jpg”>

I found a script online that allowed me to do this but it was using fopen to pull content from another website. When I uploaded the script onto one of my hosts (DreamHost), i realized that using fopen is problematic due to security. I received a “URL file-access is disabled in the server configuration” error message, which basically means that your php.ini file configuration has allow_url_fopen and allow_url_include set to OFF.

DreamHost does not allow you to pull content from another website using fopen because it’s a high risk on a shared server. Instead, they suggest other ways of getting the job done or running your own PHP. Well, the other way of getting this done would be to use cURL, and cURL is awesome because its fast and easy. So I modified the script and now it uses cURL to pull the images from outside and fopen to open and write them internally, which is fine. Feel free to download and use, enjoy!

So, how do you use this script? Well, in my normal php files, I write one include function:

<?php include ‘thisScript.php’; ?>

And then anywhere in my code where I am pulling an image from external source I write the IMG tag via my JavaScript function, like this:

<img src=”‘ . download(’http://www.flickr.com/image.jpg’).’” />

Enjoy!

Popularity: 5%


Tags:

,

,


If you enjoyed this post, please consider to leave a comment.

Comments

Work very nice, but I’m trying to cache from external domain (I don’t know if I’m clear, my english is so bad). For example, my forum is on http://www. and my images are on images. my http://www. bandwidth is so expansive that I’m trying (with your script) to put the function on my images. but I don’t find the way to put in my http://www. something like :

If you have some way to do that, I take it :)
Notify is enable :)

Best regard, Boris from France.

This is useful for Facebook Apps, due to latency of facebook for Apps, especialy de profile pic, we will try it.

thanks

Leave a comment

(required)

(required)