Here's a version for lazy people like me -- it finds all images with the 'sig-' prefix in a given directory (including gifs if your PHP serer supports them) and chooses one at random. So you just drop the image into the directory and it'll be recognised automatically. It also creates a warning image if an error occurs.
Looks complicated but it's not, really -- you use it exactly like mosquito's code, above. You can change the prefix if you need to, as well.
<?php
// Set variables
$image_dir = './';
$image_prefix = 'sig-';
$imageArray = array();
// Set image types
if(function_exists("imagegif")){
$image_types = array( 'gif', 'jpg' );
} else {
$image_types = array( 'jpg' );
}
// Get all sig images
$dir = dir( $image_dir );
while ( false !== ( $image_name = $dir->read() ) ) {
$image_info = pathinfo( $image_name );
// If it's an iamge and it starts with the correct prefix
if( in_array( @$image_info[ 'extension' ], $image_types ) && substr( $image_name, 0, strlen( $image_prefix ) ) == $image_prefix ){
array_push( $imageArray, array( 'name' => $image_name, 'type'=> $image_info['extension'] ) );
}
}
$dir->close();
// Did it find any?
if( count($imageArray) ){
// Yes
// Choose a random one
$image = $imageArray[ rand( 0, count( $imageArray )-1 ) ];
switch( $image[ 'type' ] ){
// Create a gif image
case('gif'):{
if($load_image = @ImageCreatefromgif( $image_dir . $image[ 'name' ] )){
header("Content-Type: image/gif");
Imagegif($load_image);
} else {
createErrorImage( 'Error creating gif' );
}
break;
}
// Create a jpeg image
case('jpg'):{
if($load_image = @ImageCreatefromjpeg( $image_dir . $image[ 'name' ] )){
header("Content-Type: image/jpeg");
Imagejpeg($load_image);
} else {
createErrorImage( 'Error creating jpeg' );
}
break;
}
} // END switch( $image[ 'type' ] )
} else {
// No
// Create an error image
createErrorImage( 'No images found' );
}
// Create an error image
function createErrorImage( $error ) {
$load_image = imagecreate (300, 50);
$background= imagecolorallocate ($load_image, 255, 255, 255);
$text_colour = imagecolorallocate ($load_image, 0, 0, 0);
imagefilledrectangle ($load_image, 0, 0, 150, 30, $background);
imagestring ($load_image, 1, 5, 5, "Error: $error", $text_colour);
header("Content-Type: image/jpeg");
Imagejpeg($load_image);
} // END function createErrorImage()
?>