I recently wrote about making an AJAX image gallery. In it I said you should have a separate thumbnail image so that you don’t have to load up the main image and resize it, wasting time and efficiency. In this article, I’m going to show you how to automatically make a thumbnail when an image is uploaded using PHP.

What do we need?

Well, you need a page with a form containing a file field and a page to actually upload the file and make the thumbnail out of it. We will be using the PHP GD library which will need to be part of your PHP installation. In more recent versions of PHP I think it is included as standard. The library contains a load of image manipulation tools and I would highly recommend you have a look through it to see what other effects you can achieve.

Before we start, I have to highlight the fact that this tool should not be openly available to the public unless it has extremely tight security measures on what can be uploaded. We will be making a form which uploads files directly to your server which means rogue files could fill your server with junk or much worse compromise its security. Making it public is done at your own risk!

How do we do it?

Well, the form is really simple – a standard form using POST method and having an input of type ‘file’. For this project I’m also going to include a text input for the image name, but you don’t have to. The only different bit is that the form has to have ‘enctype=”multipart/form-data”’ as one of its fields in order to handle the file correctly.

<form enctype="multipart/form-data" action="upload.php" method="POST">
	What would you like to call the image?: <input type="text" name="image_name" id="image_name" />
	<br />
	What caption should the image have?: <input type="text" name="image_caption" id="image_caption" />
	<br />
	<input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
	Pick an Image from your computer: <input name="user_image" type="file" />
	<br />
	<input type="submit" value="Upload" />
</form>

I’ve included the hidden field MAX_FILE_SIZE, but this is a really primitive form of checking the file size and is easily circumvented – you need to carry out proper checks in the next file…

The next bit is to take the file that we will get from that form and upload it to the server.

When a file is sent to another page, it is stored in one of the PHP global arrays called $_FILES. This array is kind of built in to PHP in the same way as $_GET or $_POST so you don’t need to initialize it. It is an associative array, so you can access more information about the file such as the filename, size, type etc. as well as its temporary location. When a file is uploaded, it is first put into a temporary location so that you can work out if it should be kept or thrown away. This tutorial is fairly simple and so I only have a very minor check to see if I don’t want it – I check the size and type:

// At this point you should check the size and type of the file supplied by the application.  Obviously because we are dealing with images here, the supplied file should
// be an image type.  I am restricting it to .jpeg but you will probably want to check more.
if($_FILES['user_image']['type'] == "image/jpeg" && $_FILES['user_image']['size'] < 3000000)
{
	// … accept the file
}
else
{
	// The file was the wrong format or size
?>
	<p>Error processing file.  It is the wrong format (.jpeg only) or too big.</p>
<?php
}

So, assuming that we want to keep the file, we now need to start doing some prep work for its new home on our server.

// The file supplied is valid...Set up some variables for the location and name of the file.
$target_folder = 'images/'; // This is the folder to which the images will be saved
$upload_image = $target_folder.basename($_FILES['user_image']['name']); // The new file location

This just sets up the target directory for the images to be stored in, and also the exact filename of the new image.
Now that we know where it’s going to go to, we use the move_uploaded_file PHP function to move the file from its temporary location into the newly specified home.

if(move_uploaded_file($_FILES['user_image']['tmp_name'], $upload_image)) 
{
	// Successful move…now do the image manipulation
}
else
{
	// There was a problem with the file and it wasn't moved to the server.
?>
	<p>Error processing file.  It may be too large.</p>
	<?php
}

You can see here we try to move the file from its temporary location (tmp_name) to its new location ($upload_image).

In this example, I am asking the user to specify the name of the file and also a caption for the file. Because of this, I need to get these variables and sanitize them:

include("mysql.php"); // Include the mysql file so that we can strip SQL from the variables (And we need the SQL connection later...)
 
// The following 2 variables depend on what was requested in the form - if it was only the image itself, they are unnecessary.
$newname = mysql_real_escape_string(strip_tags($_POST['image_name'])); // Get the supplied image name and sanitize it
$caption = mysql_real_escape_string(strip_tags($_POST['image_caption'])); // Get the supplied caption and sanitize it
 
// The following 2 variables specify the planned names for the 2 images (actual and thumbnail).  In this example, I specify .jpg as the extension, but if you are
// allowing multiple file extensions you may need to extend this to deal with the possibilities.
$thumbnail = $target_folder.$newname."_thumbnail.jpg"; // Set the thumbnail name
$actual = $target_folder.$newname.".jpg"; // Set the actual image name

…it’s all just about variable manipulation and this kind of thing will very likely vary from any product you build.

The next section is where we actually produce the new image in thumbnail size using some of the functions from the GD library.

// Get new sizes
list($width, $height) = getimagesize($upload_image);
$newwidth = 150; // This can be a set value or a percentage of original size ($width)
$newheight = 150; // This can be a set value or a percentage of original size ($height)
 
// Load the images
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($upload_image);
 
// Resize the $thumb image.
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
 
// Save the new file to the location specified by $thumbnail
imagejpeg($thumb, $thumbnail, 100);

The functions are fairly self-explanatory, but basically what we do is get all the sizes we need (original dimensions and new dimensions), then use the imagecreatetruecolor function to create the thumbnail ‘canvas’ using the new sizes, and load the existing image (the big one we just uploaded) using imagecreatefromjpeg. Note that this function relies on use of a jpeg…you need to use other functions such as imagecreatefromgif to handle other file types. Our final 2 stages are to copy the $source image to the $thumb image using the imagecopyresized function, then ‘print’ the $thumb image to the server using the imagejpeg function (again, for other file types use the relevant function).

Because I am wanting to specify my own name for the image, I will now rename the original:

rename($upload_image, $actual);

The last thing to do now is to put the details into the database. I am using the same database format I described for the AJAX Image Gallery tutorial which this tutorial ties in with.

if(mysql_query("INSERT INTO images (caption, thumbnail, actual) VALUES('".$caption."', '".$thumbnail."', '".$actual."')"))
{
	// ...it did work properly.  Tell the user and do anything else you particularly feel like doing.
	?>
	<p>Image Successfully uploaded!<br />Actual image: <?=$actual;?><br />Thumbnail image: <?=$thumbnail;?><br />Caption: <?=$caption;?></p>
	<?php
}
else
{
	// ...it didn't work properly.  Unlink (delete) the actual and thumbnail files and then notify the user.
	unlink($actual);
	unlink($thumbnail);
	?>
	<p>There was an error storing your image in the database.  All traces of it on the server have been deleted.</p>
	<?php
}

What we do here is evaluate the success of the SQL query. If it is successful, you can do whatever you feel like doing! Otherwise, it’s a good idea to unlink (delete) the 2 images we have just spent so long making so that they aren’t in the way for future requests.

That’s it! All the code we need is right there.

In order to use it, you have to take care that both the form and the uploading script are password protected because of their ability to put stuff on your server. Make sure that you make the target directory the right place for the gallery to find them otherwise you’ll spend ages trying to find the images knowing that you had uploaded them but not knowing where they’ve gone!

Conclusion

With a pretty short and fairly simple script we can completely automate the process of making a thumbnail when uploading an image for use in a gallery. This is a really handy thing to do because it saves the gallery having to load up a big file, only to show it as a small file.

Of course, this tutorial has also shown how to upload any file, you just have to modify the requirements for the file and change what you do with the file once you have it (after all, you don’t want to try and resize a document file do you?).

I hope this has been of use to you and you can tie it in to any projects you are working with that require thumbnails – hopefully it will make things much easier!

Remember to pop over to the forum to talk to us about web related stuff, get help with some code or just a general chat.

Download the ZIP file

Related Posts

More?

If you enjoyed this post, please consider promoting it.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Design Float
  • Reddit
  • Mixx
  • Technorati

Remeber to subscribe to the feed and get future articles delivered to your feed reader.

If you want to discuss this tutorial or any other thoughts you have then you can do so over on our fourm.

Comments

  1. thanks mate ;)
    good tutorial

  2. well written and very useful article. Thanx a lot :)

  3. Wow nice tutorial…
    is there another tutorial for the CMS news?
    thank’s

  4. this is really helpful

  5. Comment by Rzen on November 5, 2008 7:42 am

    Thank you for the tutorial it is very helpful.
    I would also like to know is there a tutorial for CMS news system?
    Cheers

  6. Comment by jamie on November 5, 2008 8:28 am

    @Rzen & junkiest:
    I’ve only just picked these comments up so sorry for the late reply!
    At the moment there isn’t a tutorial on here about any kind of CMS/News system, mostly because it’s a fairly big subject to do and at the moment we only have 2 writers both of whom are really busy with other things.
    In our forum we have a thread for tutorial suggestions so I would encourage you to flesh out your request there…here’s a link: http://progtuts.info/forum/viewforum.php?id=8. The main thing we need to know is what your overall aim is - from what you say you seem to want a news system that is built into a CMS…or do you want a standalone news system…or do you want a full CMS? The only thing I would say is that we don’t produce custom code for very specific requirements - you need a paid web designer for that - but we will try and give a general tutorial to create the type of application you want.

    Hope this is of use and feel free to ask further questions about tutorial requests over in the forum.

    Jamie

    p.s. Thanks to everyone for the comments!

Leave a Comment

(required)

(required)