php写上传图片类

做了一个上传图片类,当然 不止是可以上传图片 也可以上传各种文件......

<?php

/**

* QQ:279861795

* Author: 过往云烟

* Date: 2011-7-17

* 修改上传类型在$tupeArr那里添加

上传类*/

class FileUpdate {

private $error; //判断错误

private $maxsize; //表单大小

private $type; //上传类型

private $typeArr=array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif');

private $path; //上传目录

private $today; //获取当天目录时间

private $name; //原始文件名

private $likepath; //连接名

private $tmp; //获取临时文件名

//构造方法 初始化

public function __construct($_file,$_maxsize){

$this->error=$_FILES[$_file]['error'];

$this->maxsize=$_maxsize / 1024;

$this->type=$_FILES[$_file]['type'];

$this->name=$_FILES[$_file]['name'];

$this->tmp=$_FILES[$_file]['tmp_name'];

$this->path=ROOT_PATH.UPDIR; //创建根目录

$this->today=$this->path.date('Ymd').'/'; //创建子目录 先获取根目录路径

$this->checkError();

$this->checkType();

$this->checkPath();

$this->moveUpload();

}

//返回文件名

public function getPath(){

return $this->likepath;

}

//移动文件

private function moveUpload(){

if (is_uploaded_file($this->tmp)){ //先判断临时目录

if (!move_uploaded_file($this->tmp,$this->setNewName())){

Tool::alertback('警告:文件移动失败!');

}

}else{

Tool::alertback('警告:临时文件不存在');

}

}

//得到新文件名

private function setNewName(){

$_nameArr=explode('.',$this->name);

$_postfix=$_nameArr[count($_nameArr)-1];

$_newname=date('Ymdhis').mt_rand(100,1000).'.'.$_postfix;//得到新文件名

return $this->likepath=$this->today.$_newname;

}

//判断目录

private function checkPath(){

if (!is_dir($this->path) || !is_writeable($this->path)){

if (!mkdir($this->path)){

Tool::alertback('警告,主目录创建失败!');

}

}

if (!is_dir($this->today) || !is_writeable($this->today)){

if (!mkdir($this->today)){

Tool::alertback('警告,子目录创建失败!');

}

}

}

//验证类型

private function checkType(){

if (!in_array($this->type,$this->typeArr)){

Tool::alertback('警告:上传类型不合法');

}

}

//验证错误

private function checkError(){

if (!empty($this->error)){

switch ($this->error){

case 1 :

Tool::alertBack('警告:上传值超过了约定最大值!');

break;

case 2 :

Tool::alertBack('警告:上传值超过了'.$this->maxsize.'KB!');

break;

case 3 :

Tool::alertBack('警告:只有部分文件被上传!');

break;

case 4 :

Tool::alertBack('警告:没有任何文件被上传!');

break;

default:

Tool::alertBack('警告:未知错误!');

break;

}

}

}

}

?>

过往云烟 2011/07/29