help me on the upload class !!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

help me on the upload class !!

Post by PHPycho »

Hello forums
Now i am totally shifting towards OOP..
I had tried to make a upload class but it didnt worked .here is the code

uploader.class.php

Code: Select all

<?php
class uploader
{
	var $uploadDir;
	var $thumbDir;
	var $newFileName;
	/*var $file_name;
	var $file_type;
	var $file_size;
	var $file_temp_dir;*/
	var $fileInfo = array();
	var $maxFileSize;	
	var $allowTypes = array();
	var $errMsg = "";
	var $suMsg = "";
	/***/
	var $fileExt;	
	
	function getExtension()
	{
		$fileExt = explode(".",$this->$fileInfo['name']);
		$this->fileExt = $fileExt[1];
	}
	
	function checkTypes()
	{
		if(!in_array($this->fileInfo['type'],$this->allowTypes))
		{
			return FALSE;
		}
		else
			return TRUE;
	}		
	
	
	function doUpload()
	{
		// Check the Size
		/* If fileSize > maxSize */
		if($this->fileInfo['size'] > $this->maxFileSize)
		{
			$this->errMsg .= "File Size is larger<br />";
		}
		
		/* If fileSize == 0 */
		else if($this->fileInfo['size'] == 0)
		{
			$this->errMsg .= "No file uploaded <br />";
		}
		
		/* Check the Types */
		else if(!$this->checkTypes())
		{
			$this->errMsg .= "Invalid file type !! <br />";
		}
		
		/* If everything goes fine then Upload */
		else
		{			
			//upload to destDir
			echo "Final step";
			$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->suMsg = "Sucessfully Uploaded & Renamed !!";
			}
			
		}	
	}
	
	function deleteFile()
	{
	}
	
	function renameFile()
	{
	}
	
}
?>
action.php

Code: Select all

<?php
if(isset($_POST[] ...)
{
  include "uploader.class.php";
$uploaderObj = new uploader();
  //assign all the variable properties of uploader.class.php
$uploaderObj->doUpload();
}
?>
But nothing happens
What i want ?
1>Any techniques for checking how the class is working ie any debugging tips
2>Any changes in above code to make it efficient and effective Note: its for PHP4 ie any tips n modifications
3> when i try to echo $uploaderObj->getExtension(), it gives the follwing error
Fatal error: Cannot access empty property in C:\Program Files\xampp\htdocs\designtoko\libs\uploader.class.php on line 21
and why it is so

Thanks for reading my post.

Thanks in advance to all of you and awaiting for the results...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

hint: $this->$fileinfo
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

Thank you Mr. feyd
I got one mistake , i will try it
Again what i want is:
1>Any techniques for checking how the class is working ie any debugging tips
2>Any changes in above code to make it efficient and effective Note: its for PHP4 ie any tips n modifications
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

Thanks all of You!!
Finally i had made the uploader class...its working..

Code: Select all

<?php
//uploader.class.php
class uploader
{	
	var $uploadDir;	
	var $newFileName;	
	var $fileInfo = array();
	var $maxFileSize;       
	var $allowTypes = array();	  
	var $fileToDelete;
	var $errMsg = "";
	var $upMsg = "";	
	var $delMsg = "";
		
	function getExtension()
	{
		$fileExt = explode(".",$this->fileInfo['name']);
		return $this->fileExt = $fileExt[1];
	}
	
	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 */
		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;
	}
       
}
?>
accessing part:

Code: Select all

<?php
include "uploader.class.php";
$uploaderObj = new uploader();
$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
		{
			echo $uploaderObj->errMsg;
		}	
?>
What i want?
1> any modifications that make the code effective like one i shoulnt use explode to find the extension in case image1.name.jpg
2> i am not getting the concatenated erros, is there any effective way of assigning and displaying erros
3>any suggestions

Thanks in advance to all of You !!
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

For the errors you could add a 'getErrors' method and have your methods return true or false, then have your object return an array of errors with the getErrors method. That way you don't have to check individual properties to see if there are any errrors for each type. If you are using PHP 5 then check into exceptions.

Also, think about your properties and your method calls. Typically a public property is something that generally sticks around for the life of an object, or at least is reused between methods or multiple method calls, and method parameters are things that change on every method call. Note: this isn't set in stone, but is a way to make your object easier to use/read, you don't have to do it this way.

For example, the properties for allowTypes, maxFileSize, and uploadDir should stay as they are since you will probably only set these once.

The properties for fileinfo, fileddelete, and newFileName should probably be method parameters because they are only used once per upload.

Code: Select all

$uploader = new uploader() ;
$uploader->uploadDir = '../uploads/images' ;
$uploader->allowTypes = array('image/jpeg', 'image/jpg') ;


if( $uploader->checkFileInfo('client_img') ) 
{
  $clientImagesObj->insert($clientID,$caption); 
  $uploader->upload( $clientImagesObj->id, 'client_img' ) ;
}
else
{
  $errors = $uploader->getErrors() ;
  // do something with the errors
}
Other things you might want to add... Abliity to set permissions, checks to see if the file already exists, possibly autogenerate unique names and return the generated name to put in your record instead of inserting the record first then using the primary key.

One final thing, when writing objects like this to solve a particular task, here is a good approach that might save you time.

1. Think about the requirements. What should your object do? In this case it would probably be upload files, check the files to see if they are legit, return errors on failure, and delete files. If there are a lot then write them down.

2. Write out your interface first. A good way to do this is write some hypothetical code and pretend you are using your new object, just like in my example above. Make up methods and put them into your code with the ideal way your object will work. This way you will have the methods you need and see how they will work in your code.

3. Now that you have your methods, know what they should return and what arguments they will take, you can now code your object.
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

Thanks Mr. Begby
for your valueable suggestions..
For the errors you could add a 'getErrors' method and have your methods return true or false, then have your object return an array of errors with the getErrors method. That way you don't have to check individual properties to see if there are any errrors for each type
One more questions?
I didnt get much idea how to perform this ?
Thanks again
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

One more Question?
If i would like to generate thumbnail what should i do?
1>make another class thumbNailer.class.php
2>or use with uploader.class.php

Suggest me to make the Thumbnail script for uploader.class.php
Thanks in advance
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

PHPycho wrote:Thanks Mr. Begby
for your valueable suggestions..
For the errors you could add a 'getErrors' method and have your methods return true or false, then have your object return an array of errors with the getErrors method. That way you don't have to check individual properties to see if there are any errrors for each type
One more questions?
I didnt get much idea how to perform this ?
Thanks again

Code: Select all

class SomeClassThatUsesErrors
{

  var $errors = array() ;

  function getErrors()
  {
    return $this->errors ;
  }


  function doSomething()
  {
     // if this method fails I am going to add an error like this
     $this->errors[] = 'An error occured blah blah' ;
     return false ;
  }

}
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

PHPycho wrote:One more Question?
If i would like to generate thumbnail what should i do?
1>make another class thumbNailer.class.php
2>or use with uploader.class.php

Suggest me to make the Thumbnail script for uploader.class.php
Thanks in advance

The thumbnailer class should probably be separate since sometimes you might not be uploading images with your uploader class, and other times you might want to resize an image without doing a file upload.
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

Thanks a lot to everybody
I will try to make a thumbnailer class......
if i got any problem...there is so called forum to help us
hehhhehehe
Thanks a lot
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

I have the following code

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();			
		}		
?>
Problem with the code:
1> when i add .mp3 of very large size it gives only one error message but it should give two error messages ie it give error message "File is larger !!" but it should give "File is larger !!" & "Invalid file type !!". what is the problem with the code ?
Help !!
Thanks in advance
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

the problem is in your if/else if statements. You want to have each one be an if statement instead of if, elseif, elseif, else, otherwise only the first error will get set.
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

Post by PHPycho »

Knock Knock
anyway to perform that ?
Thanks again !!
Post Reply