PHP to upload, resize and store multiple images. April 14th, 2008 at 2:48 pm
Here is a PHP script sample that uploads multiple images, resizes the images, creates a thumbnail and stores the image pathname with descriptions in a MySQL database. The original code is modified from this example here. The major differences are the quality of images stored and the ability to store multiple images as well as a thumbnail.
For this script I’m storing the information in two separate tables. One table contains the description attributes of the image (address, price, listing number and description) with the thumbnail path and attributes (width and height). The other table contains only the images used for the slide show. The example I’m using here is to upload real estate listings. By having one table with the main images and the other table with the description and thumbnail attributes you can easily add more images to any listing.
This is just an example of the script and assumes a couple things. It assumes you have validated the user, and the input to keep your database safe. It also assumes you are using only .jpg images and does not restrict the size. As always, validate and clean your information before upload.
The first thing we need is our form for uploading the images. For this example we are going to upload 5 images of a real estate listing the MLS number(id), address, price and property description. I broke it up into two files pre-upload.php and upload.php.
pre-upload.php
<form action="upload.php" enctype="multipart/form-data" method="post"> MLS Number: <input name="mls" type="text" /> Address: <input name="address" type="text" /> Price: <input name="price" type="text" /> <input name="max_file_size" type="hidden" value="2000000" /> <input name="upload0" type="file" /> <input name="max_file_size" type="hidden" value="2000000" /> <input name="upload1" type="file" /> <input name="max_file_size" type="hidden" value="2000000" /> <input name="upload2" type="file" /> <input name="max_file_size" type="hidden" value="2000000" /> <input name="upload3" type="file" /> <input name="max_file_size" type="hidden" value="2000000" /> <input name="upload4" type="file" /> <input name="max_file_size" type="hidden" value="2000000" /> <input name="upload5" type="file" /> <input name="submit" type="submit" value="submit" /> </form>
While we added a max value size of 2mb’s to the form input this should not be used as a max size validation as the user will not get any type of error message for values above 2mb. The first image “upload0″ will be the image that is stored twice, once as thumbnail and once as a regular image.
The real work comes in upload.php. Make sure you chmod777 the folder you are going to use to upload the images.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | // connect to the database with your preferred method // now lets list the variables $mls = $_POST['mls']; $address = $_POST['address']; $price = $_POST['price']; $description = $$_POST['description']; // width and height max values for the main images. Its best to set // them both at the same value or you will end up with distorted images // if you upload both landscape and portrait layouts. $width = '640'; $height = '640'; // Here we set the name and path for the thumbnails. I chose to put the thumbs // and the main images in separate folders based on their unique MLS number. $thumbName = "images/$mls/thumb.jpg"; // Set the thumb max width and height $twidth = '250'; $theight = '250'; //first I want to make sure they actually posted an MLS number or we reject it if(empty($_POST['mls'])) { die(" You didn't enter a MLS number. Please go back "); } //now lets make sure this folder doesn't already exist so its not written over if(file_exists("images/$mls")) { die(" You are trying to add a listing that already exists "); } // so far so good lets create the directory on the server and assign the filename $oldmask = umask(0); mkdir("images/$mls", 0777); umask($oldmask); $ext = '.jpg'; $fileName = "images/$mls/"; // now we will check to see if there is a file, if there is we will put it in an array // for processing. If there is a file we are going to number them 0-5 for($i=0; $i<10; $i++) if(!empty($_FILES["upload$i"]['name'])) { $pic[$i] = $_FILES["upload$i"]['name']; } // count the total number of pictures to be resized, uploaded and stored $totalPics = count($pic); // now lets loop the process for each file for($i = 0; $i<$totalPics; $i++) // here is where you can do some file checking for example lets make sure its a .jpg. // This would also be a good place to check the file size. if (!eregi('^image/p?jpeg(;.*)?$', $_FILES["upload$i"]['type'])) { // we already made the directory so lets make sure we remove it before we kill // the script. rmdir("images/$mls"); die(" Sorry, this was not a .jpg file "); } // The images met whatever conditions you set so we move forward. else { if(is_uploaded_file($_FILES["upload$i"]['tmp_name']) and copy($_FILES["upload$i"]['tmp_name'], "$fileName$i$ext")) { // find the dimensions $simg = imagecreatefromjpeg("$fileName" ."$i". "$ext"); $currwidth = imagesx($simg); $currheight = imagesy($simg); // if its a portrait layout lets set the max height if($currheight>$currwidth) { $zoom = $width/$currheight; $newheight = $height; $newwidth = $currwidth*$zoom; } // if its a landscape else { $zoom = $width/$currwidth; $newwidth = $width; $newheight = $currheight*$zoom; } // Alright we have the dimensions sorted out now lets build the image. Using // imagecreatetruecolor() instead of imagetruecolorpalette() gives us a better // resolution $dimg = imagecreatetruecolor($newwidth, $newheight); $palsize = imagecolorstotal($simg); for($e = 0; $e<$palsize; $e++) { $colors = imagecolorsforindex($simg, $e); $imagecolorallocate($dimg, $colors['red'], $colors['green'], $colors['blue']); } imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // here is where you can set the quality I set it to 90 so they end up being fairly large imagejpeg($dimg, "$fileName" ."$i". "$ext", 90); imagedestroy($simg); imagedestroy($dimg); // Round off the width and height attributes so we can store it in the database $newheight = round($newheight); $newwidth = round($newwidth); // now lets add the main images to the database $sql = "INSERT INTO images SET filename='$fileName$i$ext', width='$newwidth', height='$newheight' "; if(mysql_query($sql)) { echo "images uploaded and resized"; } else { echo "error uploading and resizing images"; } } } // lets do it all again for the thumbnail images // The first image in the upload form "upload0' will be the image we turn into a thumb. // I added a "t" to all the thumbnail variables if(is_uploaded_file($_FILES['upload0']['tmp_name']) and copy($_FILES['upload0']['tmp_name'], "$thumbName")) { $tsimg = imagecreatefromjpeg("$thumbname"); $tcurrwidth = imagesx($tsimg); if($tcurrheight>$tcurrwidth) { $tzoom = $twidth/$tcurrheight; $tnewheight = $theight; $tnewwidth = $tcurrwidth*$tzoom; } else { $tzoom = $twidth/$tcurrwidth; $tnewwidth = $twidth; $tnewheight = $tcurrheight*$tzoom; } $timg = imagecreatetruecolor($newwidth, $tnewheight); $tpalsaize = imagecolorstotal($tsimg); for($e = 0; $e<$palsize; $e++) { $colors = imagecolorsforindex($tsimg); imagecolorallocate($tdimg, $colors['red'], $colors['green'], $colors['blue']); } imagecopyresized($tdimg, $tsimg, 0, 0, 0, 0, $tnewwidth, $tnewheight, $tcurrwidth, $tcurrheight); imagejpeg($tdimg, $thumbName, 95); imagedestroy($tdimg); $tnewheight = round($tnewheight); $tnewwidth = round($tnewwidth); } // now lets add the listing information and thumbnail information to the "listing" table $sql = "INSERT INTO listing SET mls='$mls', address='$address', price='$price', description='$description', filename='$thumbName', width='$tnewwidth', height='$tnewheight' "; if(mysql_query($sql)) { echo "Listing and information stored in database"; } else { echo "Error: Listing did not store in database"; } |
Tags: image upload, php
7 Responses to “PHP to upload, resize and store multiple images.”
M. Dubb
April 22nd, 2008 at 3:12 am
What is the database name?
It seems that entire connect to database part doesn’t exist.
Cheers
M. Dubb
April 22nd, 2008 at 3:29 am
Errors:
Parse error: syntax error, unexpected T_FOR in upload.php on line 46
This is on Line 46:
for($i=0; $i<10; $i++)
if(!empty($_FILES["upload$i"]['name'];))
{
$pic[$i] = $_FILES["upload$i"]['name'];
}
Cheers
Darren
April 22nd, 2008 at 7:22 am
Hey M. Dubb thanks for commenting.
On line 1 I wrote “connect to the database with your preferred method”. Generally I use an include and keep the database connection file separate.
Try taking out the semi-colon between “];))”
Line 41 should be
if(!empty($_FILES[”upload$i”][’name’]))
Let me know if that helps.
nast
April 30th, 2008 at 3:05 am
Hey, I also get;
PHP Parse error: syntax error, unexpected T_FOR in /Applications/MAMP/htdocs/tomas/tomp_upload.php on line 48
even though i removed the semicolon.
Paddy Callaghan
August 8th, 2008 at 9:14 am
I also recieved an error, albeit a blank page as i didn’t have errors on.
I found the error, or at least i think i did before the line mentioned above: for($i=0; $i<10; $i++)
Whatever was used to post it had change the less than sign, < to <.
Cheers
Darren
August 8th, 2008 at 9:35 am
Thanks Paddy,
For whatever reason the wordpress plugin I use to show the source code keeps escaping the character. I need to refactor this snippet anyway and turn it into a class.
Ducoci
August 16th, 2008 at 12:23 pm
hey darren!
nice script, great work!
i’m trying to adapt the code to a travel agency i’m developing their web system.
i got stuck when trying to add the paths of the images/thumbs to the mysql:
i inserted 4 file fields into the form for image uploads. the script processes and upload the files and creates the thumbnails onto the server but when it comes to insert the paths into mysql, it inserts only the first value (upload0)..
any ideas how i can get it work to add all file fields into mysql?
thanks a bunch!