Simple PHP Image Upload Form
This little chunk of PHP allows a user to upload a JPEG image and then resizes that image to generate a thumnail automatically. With a little work, you can change the file types allowed, formula for resizing the thumbnails, etc. but I wanted to keep this simple so only JPEGs are allowed and everything is resized based on height. You can view a working example here. (Upload something funny – I can always use a good laugh...)
<?php
$allowedfiletypes = array("jpeg","jpg");
$uploadfolder = "uploads/" ;
$thumbnailheight = 100; //in pixels
$thumbnailfolder = $uploadfolder."thumbs/" ;
$action = $_POST['action'];
if ($action == "upload") {
echo "<p>Uploading image... " ;
if(empty($_FILES['uploadimage']['name'])){
echo "<strong>Error: File not uploaded!</strong></p>\n\n" ;
}
else {
$uploadfilename = $_FILES['uploadimage']['name'];
$fileext = strtolower(substr($uploadfilename,strrpos($uploadfilename,".")+1));
if (!in_array($fileext,$allowedfiletypes)) { echo "<strong>Error: Invalid file extension!</strong></p>\n\n" ; }
else {
$fulluploadfilename = $uploadfolder.$uploadfilename ;
if (move_uploaded_file($_FILES['uploadimage']['tmp_name'], $fulluploadfilename)) {
echo "$uploadfilename has been uploaded succesfully.</p>\n\n";
$im = imagecreatefromjpeg($fulluploadfilename);
if (!$im) { echo "<p><strong>Error: Couldn't open image to create thumbnail!</strong></p>\n\n" ; }
else {
$imw = imagesx($im); // uploaded image width
$imh = imagesy($im); // uploaded image height
$nh = $thumbnailheight; // thumbnail height
$nw = round(($nh / $imh) * $imw); //thumnail width
$newim = imagecreatetruecolor ($nw, $nh);
imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ;
$thumbfilename = $thumbnailfolder.$uploadfilename ;
imagejpeg($newim, $thumbfilename) or die("<p><strong>Error: Couldn't save thumnbail!</strong></p>");
echo "<p><img src=\"$thumbfilename\"></p>\n\n" ;
}
}
else { echo "<strong>Error: Couldn't save file ($fulluploadfilename)!</strong></p>\n\n"; }
}
}
}
echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" enctype=\"multipart/form-data\">\n" ;
echo "<input type=\"hidden\" name=\"action\" value=\"upload\">\n" ;
echo "JPEG Image File: <br />\n" ;
echo "<input type=\"file\" name=\"uploadimage\"><br /><br />\n" ;
echo "<input type=\"submit\" value=\"Upload Image\">\n" ;
echo "</form>\n\n";
?>