Tuesday, October 23, 2007

Upload Image


<?
if(isset($_POST['submit'])) { //see if submit button is pressed.

//check if they decided to upload a pic:
if($_FILES['userfile']['size'] > 1) {

$max_size = 100000;
$max_height = 300;
$max_width = 300;

$info = getimagesize($_FILES['userfile']['tmp_name']);

//check file-size (in bytes):
if(($_FILES['userfile']['size'] > $_POST['MAX_FILE_SIZE']) ||
($_FILES['userfile']['size'] > $max_size)) {
die("<BR><BR>Error: Upload file size too large: (<b>" .
$_FILES['userfile']['size'] . "</b>). Must not exceed XX kb.");
}

//check the extension.
$array = explode(".", $_FILES['userfile']['name']);
$nr = count($array);
$ext = $array[$nr-1];
if(($ext !="jpg") && ($ext !="jpeg") && ($ext !="png"))
die("<BR><BR>Error: file extension un-recognized.
Be sure your image follows the correct extension (.JPG or .PNG)");

//CHECK TYPE: (what the browser sent)
if(($_FILES['userfile']['type'] != "image/jpeg") && ($_FILES['userfile']['type'] !=
"image/pjpeg") && ($_FILES['userfile']['type'] != "image/png")) {
die("<BR><BR>Error: Upload file type un-recognized. Only .JPG or .PNG
images allowed.");
}

//DOUBLE CHECK TYPE: if image MIME type from GD getimagesize()
//-In case it was a FAKE!
if(($info['mime'] != "image/jpeg") && ($info['mime'] != "image/pjpeg") &&
($info['mime'] != "image/png")) {
die("<BR><BR>Error: Upload file type un-recognized. Only .JPG or .PNG
images allowed.");
}

//check file size (length & width)
if(($info[0] > $max_width) || ($info[1] >$max_height)) {
die("<BR><BR>Error: Image size error (<b>" . $info[0] .
"</b> x <b>" . $info[1] . "</b>). Must not exceed ". $max_height .
" x ". $max_width .".");
}

//rename file, move it to location.
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {

//get max number of images the user has uploaded
$m = mysql_query("SELECT max(user_images) as `total_images`
FROM `images` WHERE `user_id` = '".$_SESSION['user_id']."'");
if(!$m) die('An Error Occurred.');
$result = mysql_fetch_object($m);
if($result->total_images <= 0) {
$image_number = 1;
} else {
$image_number = $result->total_images + 1;
} //end if

$filename = strtolower($_SESSION['username']) . $image_number;

if(move_uploaded_file($_FILES['userfile']['tmp_name'] ,
$_SERVER['DOCUMENT_ROOT']."/path/to/image/".$filename . '.' . $ext)) {
echo("File uploaded successfully.");
} else {
echo("An error occurred while uploading.");
}//end upload
} //end is_uploaded_file

} else { //display form ?>

<form enctype="multipart/form-data" action="<? $_SERVER['PHP_SELF']; ?>"
method="post" name="uploadImage" />
<input type="hidden" MAX_UPLOAD_SIZE = "10000" />
<input type="file" name="userfile" size="35" />
<input type="submit" name="submit" value="Upload Image">

<? } //end else ?>

No comments: