Saturday, June 13, 2009

My best method of submitting files from a html form with PHP

Uploading an image on a web server is a lot more complicated than it needs to be. If you have the means to edit your web server's config.ini file and change the upload_max_filesize variable from its default of 2MB, then you don't need me that much. However, if you are like most people and use a third party server for all of your uploads, I do have a work around for you.

First:
include the following in your html form:

<p>
<label for='cimage'><div style="width: 300px;">Image ( Must be a .jpg and < <?php echo ini_get('upload_max_filesize'); ?>b ): </div></label>
<input type='file' name='IMGlink' accept='jpg|jpeg' value='browse'>
</p>

Second:
on the page that receives your form submittal include the following:

<?php
if ((isset($_SERVER['CONTENT_LENGTH'])) && (isset($_FILES['IMGlink']["size"])))
{
if ((($_SERVER['CONTENT_LENGTH']) < 2000000) && (($_FILES['IMGlink']["size"]) < 2000000))
{
if ((($_SERVER['CONTENT_LENGTH']) > 2000) && (($_SERVER['CONTENT_LENGTH']) > 2000))
{

include 'imageupload.php';

} else { echo "You did not upload an image. Or the image you uploaded is too small. <input type='button' value='back' onclick='history.back()'>"; }
} else { echo "The .jpg file you selected is too large. It must be less than 2Mb. <input type='button' value='back' onclick='history.back()'>"; }
}
?>

Third:
create a file called 'imageupload.php'
this file will upload the submitted image to the web server
and create and upload a thumbnail of the images to the web server
and returns a string value of the filename in a variable called $url
include the following:

<?php
$idir = "uploads/images/large/"; // Path To Images Directory
$tdir = "uploads/images/small/"; // Path To Thumbnails Directory
$twidth = "200"; // Maximum Width For Thumbnail Images
$theight = "200"; // Maximum Height For Thumbnail Images

if (isset($_POST['subpage']) && $_POST['subpage'] == 'upload')
{ // Uploading/Resizing Script

$url = $_FILES['IMGlink']['name']; // Set $url To Equal The Filename For Later Use

if ($_FILES['IMGlink']['type'] == "image/jpg" || $_FILES['IMGlink']['type'] == "image/jpeg" || $_FILES['IMGlink']['type'] == "image/pjpeg") {
$file_ext = strrchr($_FILES['IMGlink']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$copy = copy($_FILES['IMGlink']['tmp_name'], "$idir" . $_FILES['IMGlink']['name']); // Move Image From Temporary Location To Permanent Location

if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbnail From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height

if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}

$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);

for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}

imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
imagejpeg($dimg, "$tdir" . $url); // Saving The Image
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful

} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}

} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';

}
}


?>

Fourth:
now take the $url variable which contains the filename of the uploaded file
and put it in your form submittal to the database:
include the following:

<?php
if (isset($_post['TheNameOfSomeVariableFromYourForm']))
{
echo "<form action='TheNameOfThePageToReceiveTheSubmittal' action='post'>";
echo "<input type='hidden' name='Url' value='".$url."'>";
// include any other form fields you would like to submit
echo "<input type='submit' value='TheNameOfYourButton'>";
echo "</form>";
}
?>

Fifth:
on the page that will receive the form submittal, receive and upload the form fields from the form submittal to the database.
if you don't know how to do that, read some of my other blog posts.

No comments: