My upload class
Posted: Sun Mar 25, 2007 10:45 pm
I have the following code
Can anybody help me on making this class more effective ?
Thanks in advance to all of you !!
Code: Select all
<?php
class uploader
{
var $uploadDir;
var $newFileName;
var $fileInfo = array();
var $maxFileSize;
var $allowTypes = array();
var $fileToDelete;
//var $errMsg = "";
var $errMsg = array();
var $upMsg = "";
var $delMsg = "";
var $randNo = "";
function getExtension()
{
$fileExt = substr(strrchr($this->fileInfo['name'],"."),1);
//$fileExt = explode(".",$this->fileInfo['name']);
return $this->fileExt = $fileExt;
}
function checkTypes()
{
if(!in_array($this->fileInfo['type'],$this->allowTypes))
{
return FALSE;
}
else
return TRUE;
}
function checkUpload()
{
// Check the Size
/* If fileSize > maxSize */
if($this->fileInfo['size'] > $this->maxFileSize)
{
//array_push($this->errMsg,"File Size is larger");
$this->errMsg[] = "File Size is larger <br />";
return FALSE;
}
/* If fileSize == 0 */
else if($this->fileInfo['size'] == 0)
{
//array_push($this->errMsg,"No file uploaded");
$this->errMsg[] = "No file uploaded <br />";
return FALSE;
}
/* Check the Types */
else if(!$this->checkTypes())
{
//array_push($this->errMsg,"Invalid file type !!");
$this->errMsg[] = "Invalid file type !! <br />";
return FALSE;
}
/* If everything goes fine then Upload */
else
{
return TRUE;
}
}
function doUpload()
{
$uploadPath = $this->uploadDir."/".$this->fileInfo['name'];
@move_uploaded_file($this->fileInfo['tmp_name'],$uploadPath);
//finally rename
$ext = $this->getExtension();
$newUploadPath = $this->uploadDir."/".$this->newFileName.".".$ext;
if(@rename($uploadPath,$newUploadPath))
{
$this->upMsg = "Sucessfully Uploaded & Renamed !!";
}
else
{
$this->upMsg = "Unable to Rename !!";
}
}
function deleteFile()
{
if(file_exists($this->fileToDelete))
{
if(unlink($this->fileToDelete))
{
$this->delMsg = "File Successfully Deleted !!";
}
else
{
$this->delMsg = "Unable to Delete the file !!";
}
}
else
{
$this->delMsg = "Such file Doesnt exists !!";
}
return $this->delMsg;
}
function getErrors()
{
return $this->errMsg;
}
function genRandomNo()
{
//using uniqid() or microtime() for unique no generation
$randNo = substr(md5(uniqid(microtime())), 0, ;
return $randNo;
}
}
?>Code: Select all
<?php
//including and creating object goes here...
$uploaderObj->uploadDir = "../uploads/images/";
$uploaderObj->fileInfo = $_FILES['client_img'];
$uploaderObj->maxFileSize = 1048576; //in bytes
$uploaderObj->allowTypes = array("image/jpeg","image/jpg");
//Check Upload and Insert the Image Contents in DB
if($uploaderObj->checkUpload())
{
$clientImagesObj->insert($clientID,$caption);
$uploaderObj->newFileName = $clientImagesObj->id;
//Finally Upload the file
$uploaderObj->doUpload();
echo $uploaderObj->upMsg;
}
else
{
print_r($uploaderObj->getErrors());
//echo $uploaderObj->getErrors();
}
?>Thanks in advance to all of you !!