Conversion tables A-K
  Conversion tables L-Z
  SPAM database query
  Reverse WHOIS utility
  North America area codes
  PHP Example forums

PHP example repository.

Web www.web-max.ca
Back to examples
Very simple image replication using FTP and GD.

This is a very basic script, again stripped down from a larger piece of code.

It allows you to replicate images across a number of servers using an "on demand" system.

The remote servers would display images using something along the lines of

<img src="http://remote.com/load_image.php?filename="cats/small/furry.jpg">

If the image does not exist locally on the remote.com server, the image is FTPed from a master location, then displayed. If image exists already, then it is simply displayed right away.

What this script does not allow for is if the file is deleted or updated on the master machine.

<?php

// Root is wherever the images may stored

$root "/var/www/html/common_images/";

// Filename is the name of the file on the
// source server

$root_file $root.$filename;

// Does it exist locally?

if(!file_exists($root_file))
{

// If no ....

    
$dir_tree explode("/",$root_file;);
    
array_pop($dir_tree);

// Make the directory for the image to sit in
// mkdirr makes recursive directories

    
mkdirr(implode("/",$dir_tree),0777);

// Open the new file in write mode

    
$fp fopen($root_file'w');

// FTP back to our source server
// You would not have to use FTP to do this,
// for the source this example came from, it was
// required.

    
$conn_id ftp_connect("ftp.server.com");

    
$login_result ftp_login($conn_id"username""password");

// FTP_GET the file into an open file handle 
// We assume the file is in the images dir ... doesn't
// have to be

    
if (!ftp_fget($conn_id$fp,"/public_html/images/".$filename;, FTP_BINARY)) 
    {
    
// Whoops
        
return;
    }
    
// else tidy up a bit

    
ftp_close($conn_id);
    
fclose($fp);
}

// So we now have the image on our server
// Just use GD to create a new image.
// We could be more intelligent here and 
// check what file the source is ... I
// just convert everything to a JPG.

$im imagecreatefromjpeg($root_file);
header("Content-type: image/jpeg");
imagejpeg($im,80);
imagedestroy($im);

function 
mkdirr($pathname$mode null)
{
    
// Check if directory already exists
    
if (is_dir($pathname) || empty($pathname)) {
        return 
true;
    }
 
    
// Ensure a file does not already exist with the same name
    
if (is_file($pathname)) {
        
trigger_error('mkdirr() File exists'E_USER_WARNING);
        return 
false;
    }
 
    
// Crawl up the directory tree
    
$next_pathname substr($pathname0strrpos($pathnameDIRECTORY_SEPARATOR));
    if (
mkdirr($next_pathname$mode)) {
        if (!
file_exists($pathname)) {
            return 
mkdir($pathname$mode);
        }
    }
    return 
false;
}
?>