php文件上传模块

     晚自习闲来无事,自己动手写了个文件上传,稍作封装,便于以后使用.

class upload
{
	private $tmp_dir;
	private $file_max_size_string;
	private $file_max_size;
	private $line;
	
	public function __construct()
	{
		$this->tmp_dir = get_cfg_var("upload_tmp_dir");
		if(is_dir($this->tmp_dir))
		{
			if($this->dir_is_write($this->tmp_dir))
			{
				$this->file_max_size_string = get_cfg_var("upload_max_filesize");
				$this->file_max_size = $this->get_size($this->file_max_size_string);
				$this->line = $this->is_winnt()?"\\":"/";
				return true;
			}
			else
			{
				return false;	
			}
			return true;
		}
		else
		{
			return false;	
		}
	}
	
	public function up($form_name,$path,$name = NULL)
	{	
		if(is_uploaded_file($_FILES[$form_name]["tmp_name"]))
		{
			$name = $name == NULL?time().rand(10000,99999):$name;
			
			if($_FILES[$form_name]["size"] > $this->file_max_size)
			{
				return false;
			}
			
			if(move_uploaded_file($_FILES[$form_name]["tmp_name"],$path.$name.".".$this->getFileType(basename($_FILES[$form_name]["name"]))))
			{
				return array(
					"type" => $this->getFileType(basename($_FILES[$form_name]["name"])),
					
					"name" => $name.".".$this->getFileType(basename($_FILES[$form_name]["name"])),
					
					"loaclname" => $_FILES[$form_name]["name"],
					
					"path" => $path,
					
					"size" => $_FILES[$form_name]["size"]
				);
			}
			else
			{
				return false;	
			}
		}
		else
		{
			return false;	
		}
	}
	
	
	/****************/
	private function dir_is_write($path)
	{
		
		if(file_exists($path))
		{
			if($this->is_winnt())
			{
				$rand_file = str_replace("\\","\\\\",$path) ."\\". rand(10000,99999).".wt";
			}
			else
			{
				$rand_file = $path."/".rand(10000,99999).".wt";
			}
			
			if(file_exists($rand_file))
			{
				return is_writable($rand_file);	
			}
			else
			{
				$fp = fopen($rand_file,"w+");
				if($fp == false)
				{
					fclose($fp);
					return false;
				}
				else
				{
					fclose($fp);
					$isw = is_writable($rand_file);
					while(file_exists($rand_file))
					{
						unlink($rand_file);
					}
					return $isw;
				}
			}
		}
		else
		{
			return false;	
		}
	}
	
	private function is_winnt()
	{
		if(PHP_OS == "WINNT")
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	private function get_size($size_string)
	{
		$size_string = strtoupper($size_string);
		$size = substr($size_string,0,strlen($size_string)-1);
		$dw = substr($size_string,strlen($size_string)-1,1);
		$jz = $this->is_winnt()?1024:1000;
		switch($dw)
		{
			case "K":
				return $size * $jz;
			case "M":
				return $size * $jz * $jz;
			case "G":
				return $size * $jz * $jz * $jz;
			default:
				return $size_string;
		}
	}
	
	private function getFileType($name)
	{
		$arr = explode('.',$name);
		return $arr[count($arr) - 1];
	}
}
posted @ 2011-03-13 21:43  Eslizn  阅读(163)  评论(0编辑  收藏  举报