Tuesday, March 23, 2010

PHP File Upload

1. Setup .ini file within the directory to include the following lines:
post_max_size = 10000000
upload_max_filesize = 10000000

2. Make sure that HTML code contains the MAX_UPLOAD_SIZE hidden field

3. Use the following codes:
function uploadPicture() {

$uploaddir = "issuepics";

$pext = getFileExtension($_FILES['txtImgFile']['name']);
$pext = strtolower($pext);

if (($pext != "jpg") && ($pext != "jpeg"))
{
unlink($_FILES['txtImgFile']['tmp_name']);
return "Error: Extensions Unknown, only JPEG is allowed.";
}

// Resize image
$imgsize = getimagesize($_FILES['txtImgFile']['tmp_name']);
$imgfile = $_FILES['txtImgFile']['tmp_name'];

if (($imgsize[0] > 640) || ($imgsize[1] > 480))
{
$tmpimg = tempnam("/tmp", "MKUP");
system("djpeg $imgfile >$tmpimg");
system("pnmscale -xy 640 480 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile");
unlink($tmpimg);
}

// Rename image
global $finalFileName;
$finalFileName = getRandomKey() . "." . $pext;
$newfile = $uploaddir ."/" . $finalFileName;

// copy image into directory
if (is_uploaded_file($imgfile))
{
if (!copy($imgfile,"$newfile"))
{
return "Error: Problem uploading file";
}
}

unlink($imgfile);

return "";

}

function getRandomKey() {
$rand = time() . rand(0,1000);
return $rand;
}

No comments: