t218.php
<?php
//case 29 文件上传类
//上传类
class upload
{
//私有,文件类型数组
private $allow_types = array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif');
//文件尺寸
private $max_size = 1048576;
//图片目录
private $upload_path = './img/';
//错误提示
private $error = '';
/**
* @param $file 上传文件的数组数据
* @param string $prefix 文件名前缀
* @return bool|string 成功返回上传文件的目录地址,失败false
*/
public function up($file,$prefix='')
{
//有错误时
if($file['error'] != 0)
{
$upload_errors = array(
1=>'文件过大,超过了php配置的限制',
2=>'文件过大,超过了form表单的限制',
3=>'文件没有上传完毕',
4=>'文件没有上传',
6=>'没有找到临时上传目录',
7=>'临时文件写入失败',
);
$this->error = isset($upload_errors[$file['error']])?$upload_errors[$file['error']]:'未知错误';
return false;
}
//类型不符
if(!in_array($file['type'],$this->allow_types))
{
$this->error = '此类型不能上传,允许的类型为:'.implode('|',$this->allow_types);
return false;
}
//文件过大
if($file['size'] > $this->max_size)
{
$this->error = '文件不能超过'.$this->max_size.'字节';
return false;
}
//生成一个随机id+扩展名
$new_file = uniqid($prefix).strrchr($file['name'],'.');
//子目录
$sub_path = date('YmdH');
//全路径
$upload_path = $this->upload_path.$sub_path;
//判断不是目录时,建立目录
if(!is_dir($upload_path))
{
mkdir($upload_path);
if(move_uploaded_file($file['tmp_name'],$upload_path.'/'.$new_file))
{
return $sub_path.'/'.$new_file;
}
else
{
$this->error = '移动失败';
return false;
}
}
}
public function getError()
{
return $this->error;
}
}
t219.php
<?php
header('content-type:text/html;charset=utf-8');
//引入文件上传类
require_once ('./t218.php');
//声明图片路径
$pic_path = '';
//
if(isset($_POST['up_load']))
{
//实例化
$up_load1 = new upload();
//上传
if(!($pic_path = $up_load1->up($_FILES['pic'],'user_')))
{
echo $up_load1->getError();
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>测试上传文件类</title>
</head>
<body>
<h2>编辑用户头像</h2>
<p>用户名:小明</p>
<p>现有头像:</p>
<img src="<?php echo './img/'.$pic_path;?>" onerror="this.src='./img/default.jpg'">
<form action="./t219.php" method="post" enctype="multipart/form-data">
<p>上传头像:<input name="pic" type="file"></p>
<p><input type="submit" name="up_load"></p>
</form>
</body>
</html>