php上传类(安全上传类)
[php]
<?php
//php文件上传类
//author: lenix 2014.10.7<!--more-->
header("Content-Type:text/html; charset=utf-8");
date_default_timezone_set("Asia/Shanghai");
class UploadFile
{
private $imageType=["image/gif","image/jpeg","image/jpg","image/png","image/x-png","image/bmp","image/x-ms-bmp","image/pjpeg"];//图片类型
private $fileType=["application/zip","application/msexcel","application/xml","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/mspowerpoint","application/vnd.ms-powerpoint","application/pdf","application/x-shockwave-flash","application/x-rar-compressed","application/x-rar","audio/mpeg","audio/x-ms-wma","flv-application/octet-stream","audio/x-ms-wmv","video/mp4","video/x-flv","audio/x-wav","application/msword","video/mpeg"];//文件类型
private $tmpName;
private $fileName;
private $error;
private $fileSize;//上传文件大小
private $maxSize=10000000;//最大允许上传大小
private $upName;
private $upDir="uploadfile/";//上传目录
//构造函数 默认为图片上传
function __construct($upType="image")
{
$this->tmpName = $_FILES["file"]["tmp_name"];
$this->fileName = $_FILES["file"]["name"];
$this->error = $_FILES["file"]["error"];
$this->fileSize = $_FILES["file"]["size"];
$this->upName=date('Y') . date('m') . date('d') . uniqid();//生成随机文件名
//判断文件大小
if ($this->fileSize > $this->maxSize) exit ("文件超过".($this->maxSize / 1024 / 1024)." M大小");
if ($this->error > 0) exit($error);//判断上传错误
if ($upType== "image") {
$this->checkImage();
}else{
$this->checkFile();
}
$this->uploadFile();
}
//检测图片类型
function checkImage()
{
$ftype=getimagesize($this->tmpName);
if (!in_array($ftype['mime'],$this->imageType)) {
exit("非法图片类型");
}
}
//检测文件类型
function checkFile()
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype= finfo_file($finfo, $this->tmpName);//根据文件内容来判断文件类型
finfo_close($finfo);
if (!in_array($ftype,$this->fileType)) {
exit("非法文件类型");
}
}
//获得文件扩展名
function getExtension($fileext)
{
return pathinfo($fileext, PATHINFO_EXTENSION);
}
//上传文件
function uploadFile()
{
if (!is_uploaded_file($this->tmpName)) {
exit("非法上传");
} else {
move_uploaded_file($this->tmpName,
//"upload/" . $_FILES["file"]["name"]);
$this->upDir . $this->upName .'.'. $this->getExtension($this->fileName));
echo "上传为: " . $this->upDir . $this->upName .'.'. $this->getExtension($this->fileName);
}
}
}
$up=new UploadFile();//上传图片
//$up=new UploadFile("file");//上传文件
?>[/php]
最后更新于 2015年1月30日