When handling image uploads through your website, whether this be for blog posts or user submitted content, it may be required to create thumbnail versions of uploaded images. In this tutorial I will be walking you through handling an upload, detecting the file type and saving both the original and scaled thumbnail to a directory.
Skip the tutorial and download the files.
One way in which this system will differ from others is that the thumbnail we create will be generated by scaling the image to a preset maximum width / height and then adjusting the other by that ratio. By doing this you ensure the whole image will be displayed and not focused in on the centre or top corner. This does have a drawback, when uploading large, square images you may find that the thumbnail becomes too small and details cannot be seen.
First we handle the image upload, I won’t go into too much detail here as the tutorial is focusing mainly on the thumbnail creation, though I will outline the basics.
<form method="post" action="/upload.php" enctype="multipart/form-data"> <input type="file" name="upload" id="upload" /> <input type="submit" id="final-upload" value="Upload Image" /> </form>
Once the image has been uploaded we can start handling the data and uploading our images. On the page that will handle the upload ( in this scenario it is upload.php ) we need to write the following code. I have commented the code throughout to provide an explanation of it’s functionality.
Firstly, we check that the form has been submitted and that a file was entered. We also define a small number of variables that we will use throughout the program.
<?php
define( 'MAX_FILESIZE', 20000 );
define( 'UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . 'uploads/' );
if( !empty( $_FILES['upload'] ) && $_POST )
{
...
}
?>
Then, we will do some error code checking, this is mainly for debugging purposes though can prove useful should the user upload something you aren’t ready to handle.
if( !empty( $_FILES['upload']['error'] ) )
{
switch( $_FILES['upload']['error'] )
{
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'No error code avaiable';
}
}
We will then proceed to create some additional error checking. The following checks make sure that an upload has been detected, the file is of type image and the file size does not exceed a preset limit ( servers need love too ).
// Was file uploaded?
elseif( empty( $_FILES['upload']['tmp_name'] ) )
{
$error = 'No file was uploaded.';
}
// Is the file an image?
elseif( !preg_match( '|image/|', $_FILES['upload']['type'] ) )
{
$error = 'File is not an image.';
}
// Is the file small enough?
elseif( $_FILES['upload']['size'] > MAX_FILESIZE )
{
$error = 'File is too big.';
}
Now that we have the error checking done and dusted we can start handling the upload.
if( !$error )
{
// Find the uploaded file extension
$ext = substr( $_FILES['upload']['name'], strrpos( $_FILES['upload']['name'], '.' ) + 1 );
// If the main file has uploaded, proceed to create the thumbnail
if( move_uploaded_file( $_FILES['upload']['tmp_name'], UPLOAD_PATH . $_FILES['upload']['name'] ) )
{
$main_image = UPLOAD_PATH . $_FILES['upload']['name'];
// Create the thumbnail
$make_thumb = create_thumb( $main_image, 100, 100, UPLOAD_PATH . 'thumb_' . $_FILES['upload']['name'], $ext );
// Check that the thumbnail was created
if( !$make_thumb )
{
$error = 'Thumbnail was unable to be created.';
}
}
else
{
$error = 'Failed to upload image. Ensure directories are created properly.';
}
}
Now we have the entire script handling the image upload. But there is one task left, and that is to add the function that actually creates the thumbnail. Since this is quite a large function I have added internal commenting for you to read through.
function create_thumb( $imgSrc, $thumbnail_width, $thumbnail_height, $dest_src, $ext )
{
//getting the image dimensions
list( $width_orig, $height_orig ) = getimagesize( $imgSrc );
// Check if the images is a gif
if( $ext == 'gif' )
{
$myImage = imagecreatefromgif($imgSrc);
}
// Check if the image is a png
elseif( $ext == 'png' )
{
$myImage = imagecreatefrompng($imgSrc);
}
// Otherwise, file is jpeg
else
{
$myImage = imagecreatefromjpeg($imgSrc);
}
// Find the original ratio
$ratio_orig = $width_orig / $height_orig;
// Check whether to scale initially by height or by width
if( $thumbnail_width / $thumbnail_height > $ratio_orig )
{
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
}
else
{
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width / 2; //horizontal middle
$y_mid = $new_height / 2; //vertical middle
$process = imagecreatetruecolor( round( $new_width ), round( $new_height ) );
// Scale the image down and the reduce the other axis to create the thumbnail
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
// Depending on the file extension, save the file
if( $ext == 'gif' )
{
imagegif( $thumb, $dest_src );
}
elseif( $ext == 'png' )
{
imagepng( $thumb, $dest_src );
}
else
{
imagejpeg( $thumb, $dest_src, 100 );
}
// Remove rubbish file data
imagedestroy($process);
imagedestroy($myImage);
// Return thumb ( success / fail )
return $thumb;
}
Now that we have our function set up we can proceed to call it when the file it uploaded. Under your function you can now run the following code to create your thumbnail and upload it under the same name as the uploaded file.
// Find the extension of the uploaded file $ext = substr( $_FILES['upload']['name'], strrpos( $_FILES['upload']['name'], '.' ) + 1 ); // Create the thumbnail in the same directory create_thumb( $_FILES['upload']['tmp_name'], 100, 100, $_FILES['upload']['name'], $ext );
There are most likely a number of security additions you can make to this function and feel free to leave any good ones in the comments. Any questions or comments are always appreciated. Just leave a message in the comments section below and I will get back to you.














If I fill in the form I get redirected to a blank page upload.php, no mather wich extension i try to upload.