In this week’s screencast, I’ll show you how to upload files and then have PHP dynamically create a thumbnail. Whether you’re building an ecommerce site, or just a simple gallery, these techniques will absolutely prove to be useful. If you’re ready for your “spoonfed” screencast of the week, let’s get going!
*Note – There have been a few slight changes to the code after some additional thinking and some great suggestions. Don’t worry, very little has changed. Just some cleanup. You can review the changes below, and/or download the source code.
The Simple Config File
The first step is to create a simple config file where we can store a few variables. By placing these in their own file, we can easily make changes to our code without having to edit many lines.
$final_width_of_image = 100; $path_to_image_directory = 'images/fullsized/'; $path_to_thumbs_directory = 'images/thumbs/';
- $final_width_of_image – This variable will store the width of our thumbnail.
- $path_to_image_directory – This stores the path to our full sized images folder
- $path_to_thumbs_directory – This stores the path to our full thumbnails directory
Save this file as ‘config.php’ and place it in the root of your folder.
The HTML
Next, create a new page called “index.php” and paste the following.
<?php
require 'config.php';
require 'functions.php';
if(isset($_FILES['fupload'])) {
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
$filename = $_FILES['fupload']['name'];
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
createThumbnail($filename);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="" />
<title>Dynamic Thumbnails</title>
</head>
<body>
<h1>Upload A File, Man!</h1>
<form enctype="multipart/form-data" action="" method="post">
<input type="file" name="fupload" />
<input type="submit" value="Go!" />
</form>
</body>
</html>
First, scroll down a bit to the body tag. To keep things as bare-bones as possible, I’ve created an extremely simple form. But it will get the job done just fine.
<form enctype="multipart/form-data" action="" method="post"> <input type="file" name="fupload" /> <input type="submit" value="Go!" /> </form>
Any time that you’re going to be working with the “file upload” input type, you need to add an “enctype” attribute to the form tag.
<form enctype="multipart/form-data"
Rather than posting to a different page, we’ll just write the code in our main document. To do that, we’ll set the action attribute equal to this page.
action="<?php print $_SERVER['PHP_SELF']
Now, scroll back up to the PHP code at the top. We’re requiring two files. The first is the config file that we just created. The second one is “functions.php” – which we’ll create shortly.
Next, we’re checking to see if the page has posted back. If it has, we’ll then check to see if the file that the user chose was either a “jpg”, “gif”, or “png”. We can do this by checking the file name against a regular expression.
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name']))
To learn more about regular expressions, watch this screencast.
Moving along, we’re creating a few variables.
- $filename - Stores the name of the file that the user has chosen to upload.
- $source – When the submit button is clicked, the file will be saved into a temporary directory. This variable will store that path.
- $target – This will store the path of where the uploaded image should be saved.
Saving the File
The final step is to move the file from the temporary directory into our “images/fullsized” folder. We can do this by calling the move_uploaded_file() function. We’ll pass in two parameters. The first one needs to know the path to the temporary folder. The second needs to know where to save the file. ($source and $target, respectively)
move_uploaded_file($source, $target);
Creating the Thumbnail
Rather than store all of the code in our index.php page, let’s create another page called “functions.php”. Create and open this new file and write a new function called “createThumbnail()”.
function createThumbnail($filename) {
require 'config.php';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
We’ll start by requiring the “config.php” file once again. Next, we’ll check to see whether the user selected a “jpg”, “gif”, or “png”. We must do this because PHP requires a different function depending on the file: “imagecreatefromjpeg”, “imagecreatefromgif”, “imagecreatefrompng”.
After that, we must store the width and height values of the image that the user chose to upload. We can do this by calling “imagesx”, and “imagesy”, respectively.
$ox = imagesx($im); $oy = imagesy($im);
Next, we’ll create two more variables that will store the width and height values for the thumbnail that will soon be created.
- $nx – is equal to the value from our config file: 100
- $ny. We’ll need to run some simple math to find the correction proportionate height.
$nx = $final_width_of_image; $ny = floor($oy * ($final_width_of_image / $ox));
ImageCreateTrueColor
In our case, we’re passing in the “$nx”, and “$ny” variables that we just created.
Image Copy Resized
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
Saving the Thumbnail
The final steps require that we check to see if a “thumbnails” folder exists. If it doesn’t, we’ll create it by using “mkdir”. Then, we’ll output our new image to the thumbnails folder.
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
Finally, we need to echo out the thumbnail to show the user that his image was uploaded successfully.
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />'; $tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.'; echo $tn;
Finished
Well done! This screencast was somewhat hastily done – because of time constraints. You might want to clean up the code a bit and a bit more error handling.
If you wish to take things further, see if you can figure out how to crop the images as well! As always, I’m more than open to refinement and suggestions!
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.






Nice, this is really useful. Bookmarked..
so if there is already an image in the folder with that name what will happen?
this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
copy of this lesson on my site here
http://www.majlesnet.com
Another problem with the preg_match in this tutorial is that uppercase extensions such as .JPG will fail, even if they are a perfectly good image.
Thought that might save someone a few hours of beating their head against their desk.
Also for anyone intersted in sharpening their image once it has been uploaded check out imageconvolution(); (PHP 5+)
Jeffery or Bernk,
Any chance of expanding on how to improve the resolution of the thumbs, seem to always come out pixelated?
Jeffery… love the tut, thanks.
http://us2.php.net/imagick
ImageMagick will do a much better job with far less code. You can even do sharpening and other effects.
There is also a php function for determining file type and extension. I don’t know why the above code got though with so many obvious mistakes.
this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
copy of this lesson on my site here
http://www.ac-coven.net
Does this crop the thumb? Or just resize? I’m looking for something to crop the image to 100×100, everything i’ve found was rather difficult to implement with my current code.
very interesting. Anything related to digestion is a pretty personal topic. If you’re interested in more info based on mass response to this, check out this watch bones page
Hi I’m new to this. But I was wondering what I would change to allow the users to browse and get a file and send the file in a form to be received in an email. I guess kinda like how an email attachment would work.
Hi i have just used your code to create a mock up gallary website, but i was wondering if it is posible to change the code so that the user would be able to upload more than one image at a time and also to be able to organice the images into sections, i guess that this would be done by using arrays and also by using sub folders within the thumbnails directiory and or the image directory. Please could some one help get back to me with this as soon as posible.
How can I allow a larger file to be uploaded?
Where do you go to set permissions. The code will work on my site server, but not on wamp..
Nice tut Jeffrey,
Only the scaling doesnt work. If i upload an image that is 600 * 480 px. The thumb will get 100 * 100 px; Thomas said anything about getimagesize() but how do i apply.
For some reason the file is moving to the correct location but not creating a thumb. I get no errors either? Any ideas as to why it will move the file but not resize it?
very nice work… was very helpful….
Nice tutorial,very useful and understanding to the php beginners like me.
Well. nice one!
Where can i download the source code? – I can’t find it on your page.
Can anyone guide me please
hi
i like your tutorial. but can you tell how we can create more than one thumnail images.
for example, if i upload 1024×768 size image, it saves on server, also a thumnail of 120×90 generates and saves on the server with the help of the above script. I also want to create and save to server another image sized 800×600.
Please tell me how to do this.
Hey all!
To begin, great job! Love all the community involvement and different code to build upon the solid foundation. I’m still first month w/ php and this was fun and productive for me.
I am, however, continuing to experience the issue with the thumbnail error message. I have apache and php running on a local drive for dev. purposes, and all permissions are wide open. Also the code looks solid, but I may be missing something…
Any ideas why this would be failing out on me? If anyone wants my files just email me.
Alrighty scratch the last, finally found that my thumb directory variable name was different in config.php than what I had in functions.php… now I get the congratulatory message but a broken image, trying to upload multiple unique .jpg images with same issue, and the images are not appearing in the fullsized nor thumbs directories…
Okay so everything is running now, but images are just going in to the root of the images folder named “fullsizedxxxxxxxx.jpg” and “thumbnailxxxxxx.jpg” – rather than being sent to the appropriate fullsized and thumbnail folders specified in the code.
Is this a typo I’m missing or a known issue by anyone…???
This is absolutely usefulllll! Thanks!
you shud share the code for download.
Hi Jeffery,
Great tutorial, but it doesn’t seem to work for me. Do I need a certain PHP version / setting. In addition, I am getting various errors. One of them being:
arning: imagesx(): supplied argument is not a valid Image resource.
Please help.
Best Regards,
Kam
nice tutorials thanks a lot
Nice tutorial, in depth and to the point.
I have found an issue, your regular expressions seem messy:
if(preg_match(‘/[.](jpg)|(gif)|(png)$/’, $_FILES['fupload']['name'])) {
Could be transformed into:
if(preg_match(‘/\.(jpg|gif|png|jpeg)$/’, $_FILES['fupload']['name']) ) {
* Added case insensitivity & jpeg extension. Also grouped them better and escaped the period which matches any character if left unescaped.
And the best way to validate if its an image or not would be the getimagesize on the uploaded file:
list($width, $height, $type, $attr) = getimagesize( $uploaded_file );
if(preg_match( ‘/^image\/(jpeg|jpg|gif|png)$/’, $type ) ) {
Hope you like my suggestions.
you helpet me a lot dear friend…
Thankyou so much
So I uploaded the files and nothing happens. The page just reloads and images are not added :/
nice tutoirla, one month ago i tried this and failed. Tried again it today and it work great, because i increase my php knowledge
i just paid $9 thinking it would open some jquerified window on this page with the golden ticket to the source code. after all, it explicitly says under the screencast video, in italics:
“*Note – There have been a few slight changes to the code after some additional thinking and some great suggestions. Don’t worry, very little has changed. Just some cleanup. You can review the changes below, and/or download the source code.”
is this an oversight on net tuts’ part?
Nice Work. And bundle of thanks. Dear.
God Bless You
What if i want to make my upload component in flash?
nice work but how can i change? the size of the height, i want my picture thumbnails to be 300 x 300.
Please help me.
The script looks very nice, but I can’t get it into my theme options page
From wordpress
have my man babies! your tutorials make my day heh.
thnx for your efforts bro!
its very nice tutorial.. Thanks…
Thank you for your efforts in setting this up. I must say I was just looking for a sample on how to create a Thumb, and well this is the way to go for me. Many thanks, may the force be with you!
A very nice screencast / tutorial. thank you very musch, but I have an issue with uploading image files that are slightly larger in file size (>4Mb ). The settings in php.ini for file upload are modified. Is there a way to fix this for this script?
in you .htaccess file you can add
php_value max_upload_filesize 10M
change 10 to what ever you want.
Hey Fellas, Im getting an error.
Warning: imagecreatefromjpeg(http://www.imperativedesign.net/images/01494_lonesomehouse_1280×960.jpg) [function.imagecreatefromjpeg]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/content/p/b/a/pbar7268/html/functions.php on line 75
I checked the php.ini file and the allow url open was set to off. I tried the following to no avail.
allow_url_fopen = on
allow_url_fopen = 1
if(!$im){
echo ‘problem creating thumbnail’; die(‘Cannot make the thumbnail’);
}
I put this check in after its supposed to create the thumbnails and its telling me there is no im.
Any suggestions?
Thanks
Nice tutorial thanks a lot!
thaaaaaaaaaaaaanks
this is a great tutorial, but I see some simple problems that you need to take into consideration
for example what if the file extension is CAPS ex. “.JPG” or “.PNG”
the second problem that I see is. If you try to upload a file that ends in gif of png it will get uploaded. Ex. “FILEpng” or “FILEgif”.
I know its not hard to fixed but most people don’t test like/for that.
here is how I fixed those two problem
if( preg_match(“(\.jpg)|(\.png)|(\.gif)$”, $_FILES['fupload']['name'] ){
….
}
sorry I made a miss with this.
if( preg_match(ā/(\.jpg)|(\.png)|(\.gif)$/iā, $_FILES['fupload']['name'] ){
ā¦.
}
I know this is late in the game but hopefully you can help. I am writing an admin page for my users which allows them to upload photos to their section of the website using this script and it has my head banging against a wall.
In the config file, I changed it slightly to read
$path_to_image_directory = ‘../’.$website_name.’images/fullsized/’;
$path_to_thumbs_directory = ‘../’.website_name.’images/thumbs/’;
The script will upload the file to the full sized folder but not to the thumbs folder. Error messages I keep getting are
..//images/fullsized/somephotojpg/ failed to open stream not such file or directory exists….
The error bothers me because when I check the full sized folder, there is the photo yet the thumbs folder is empty. By the way I actually get a slew of error messages are that all relating to not finding the file.
I am calling the $website_name from a MySql call pulling in the variable. All other fields queried from the database populate with corret values including the $website_name.
Please a little help.
as i can see you are trying to upload a large image something like 1280×960 which can not be uploaded because of the php limitations…
if your file size exceeds upload_max_file setting in php.ini, php simply does not upload that file and NEVER gives an error… so the script wont be able to find that image since it’s not uploaded… i think this is why you get that error…
also there is other limitations… if you are working with large images, GD library consumes high memory… so if the memory that’s needed to process your image exceeds memory_limit in your php.ini file.. it can not proccess that image…
and also make sure to increase max_execution_time in your php.ini file…
Shortly, try to increase upload_max_filesize, post_max_size and memory_limit settings in php.ini
hope this helps
Regards
PDesignX