Monday, June 1, 2009

Upload Image With PHP

This example provides the uploaded image width and height before uploading the image which will be useful to restrict the users from uploading the large images.

//checks if the form has been submitted
if(isset($_POST['submit']))
{
//upload directory where the file will be stored
$uploaddir = 'uploads/';

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

$uploadfiles = basename($_FILES['userfile']['name']);

list($width, $height, $type, $attr) =
getimagesize($_FILES['userfile']['tmp_name']);

if (file_exists($uploadfile)) {
//print error message
echo $uploadfiles;
echo "- file already exists");
die();
} else {
echo "The file $uploadfiles does not exist
";
}


if ($width > 80 || $height > 80)
{
//print error message
echo "Maximum allowed size is 80x80 pixels";
die();
}


if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "
Image Uploaded Successfully!

";

echo "
Image Width: ";
echo $width;
echo "
Image Height: ";
echo $width;
echo "
Image type: ";
echo $type;
echo "
Attribute: ";
echo $attr;
echo "
";
} else {
//print error message
echo "
File was not successfully uploaded

";
die();
}

}else{

?>

<form enctype="multipart/form-data" method="post" action="index.php">
<TABLE><TR><TD>
//define a maxim size for the uploaded images
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Send this file: <input name="userfile" type="file">
</TD></TR><TR><TD>
<input type="submit" name="submit" value="upload">
</form>
</TD></TR></TABLE>

}
?>

0 comments:

Post a Comment