Return to Snippet

Revision: 47758
at June 15, 2011 22:42 by xylude


Initial Code
class uploadFile
	{
		public $target;
		public $finalFileName;
		public $elementId;
		public $checkSize;
		public $allowOverwrite;
		public $emptyFolder;
		public $createFolder;
		
		function upload()
			{
				if(!isset($this->finalFileName)) { $this->finalFileName = basename($_FILES[$this->elementId]['name']); }
				if(!isset($this->allowOverwrite)) { $this->allowOverwrite = false; }
				if(!isset($this->emptyFolder)) { $this->emptyFolder = false; }
				if(!isset($this->createFolder)) { $this->createFolder = true; }
				 
				$type = $_FILES[$this->elementId]['type'];
				$fileTarget = $this->target . $this->finalFileName;  
				$ext = substr($this->finalFileName, -3);
				
				$fileBeginning = str_replace('.','',$this->finalFileName);
				
				if($this->checkSize)
					{
						if(isImage($type))
							{
								$size = getimagesize($_FILES[$this->elementId]['tmp_name']);
								if($size[0] > 500 || $size[1] > 500)
									{
										return false;
									}
							}
					}
							
				if(!checkForInvalidChars($fileBeginning))
					{
						return false;
					}
				if($this->emptyFolder)
					{
						$getFile = new getFileNameFromFolder();
						$getFile->folderName = $this->target;
						$filename = $getFile->returnFileName();
					}
				if(!file_exists($this->target)&&$this->createFolder)
					{
						mkdir($this->target,0777,true);
					}	
				
				if(file_exists($fileTarget)&&!$this->allowOverwrite) { return false; }
				
				if(move_uploaded_file($_FILES[$this->elementId]['tmp_name'], $fileTarget)) 
					{
						if($this->emptyFolder&&$filename!="File/Folder doesn't exist.") { unlink($this->target.$filename); } //only unlink if file upload was successful and there is a previous file in the folder.
						return true;
					} 
				else 
					{
						return false;
					}
			}
	}
/*
properties:
elementId - the name of the element submitting the file
finalFileName - defaults to the file name, change it if you want to store it with a diff. name
target - the location you wanna store the file in
checkSize - will do a check against the image type/size you may wanna modify that to suit your needs
allowOverwrite - defaults to false, true = overwrite file if it exists, false = don't
emptyFolder - defaults to false, true = empty target folder contents before uploading
createFolder - defaults to true, true = create folder if it doesn't exist.

methods:
upload() - uploads the file.
*/

Initial URL


Initial Description
You may wanna mess with it to suit your needs (like setting the folder to 0777).

Initial Title
File Upload Class

Initial Tags
php

Initial Language
PHP