Php: external caching script

Status
Not open for further replies.

iMaarten

Member
12
2011
0
0
Hello, i'm looking for a script that caches data (mostly images) from an external site to my own server. Example: MYSITE/cache.php?=image.png: cache.php gets image.png from an external site and saves it to the server and sent the local copy the next time image.png is requested
 
6 comments
you may run a script on specific db tables to make the following:

  1. get data from database
  2. seeks for img tags (regex)
  3. downloads the image file
  4. replaces the original image url in the article
  5. saves the new article
8-)
 
i assume you always have to download only from one site, see the code below
PHP:
    $url = 'site.com/cache.php?=image.png';
    $url = parse_url($url,PHP_URL_QUERY);
    $imgFile = preg_replace("/^=/","",$url);
    // set your images folder path here
    $imagesPath =  " images/".$imgFile;

    if(!file_exists(($imagesPath))) {
        
        // i assume you always have to download from only one website
        // i.e http://thatsite.com/image.png
        
        $otherSiteUrl  = 'http://thatsite.com/' .  $imgFile;
        if(!file_put_contents($imagesPath, file_get_contents($otherSiteUrl))){
            echo 'Failed to download file';
            $imagesPath = null;
        }
    }
    echo $imagesPath;

edit: if you wants to display the image itself instead of echo location to it, replace echo $imagesPath with below code
PHP:
if(!empty($imagesPath)) {
        $fileParts  = pathinfo($imagesPath);
        $fileExtenstion = $fileParts['extension'];
        switch( $fileExtenstion ) {
        case "gif":
            $type="image/gif";
        break;
        case "png":
            $type="image/png";
        break;
        case "jpg":
            $type="image/jpg";
        break;
        default:
            $type="image/jpg";
        }
        header("Content-Type: $type");
        readfile($imagesPath);
    }
 
Last edited:
Status
Not open for further replies.
Back
Top