php上传类(安全上传类)

dafenqi
2023-08-07 / 0 评论 / 8 阅读 / 正在检测是否收录...

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-&gt;tmpName = $_FILES["file"]["tmp_name"];
$this-&gt;fileName = $_FILES["file"]["name"];
$this-&gt;error = $_FILES["file"]["error"];
$this-&gt;fileSize = $_FILES["file"]["size"];
$this-&gt;upName=date('Y') . date('m') . date('d') . uniqid();//生成随机文件名
//判断文件大小
if ($this-&gt;fileSize &gt; $this-&gt;maxSize) exit ("文件超过".($this-&gt;maxSize / 1024 / 1024)." M大小");
if ($this-&gt;error &gt; 0) exit($error);//判断上传错误
if ($upType== "image") {
$this-&gt;checkImage();
}else{
$this-&gt;checkFile();
}
$this-&gt;uploadFile();
}


//检测图片类型
function checkImage()
{
$ftype=getimagesize($this-&gt;tmpName);
if (!in_array($ftype['mime'],$this-&gt;imageType)) {
exit("非法图片类型");
}
}


//检测文件类型
function checkFile()
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype= finfo_file($finfo, $this-&gt;tmpName);//根据文件内容来判断文件类型
finfo_close($finfo);
if (!in_array($ftype,$this-&gt;fileType)) {
exit("非法文件类型");
}
}


//获得文件扩展名
function getExtension($fileext)
{
return pathinfo($fileext, PATHINFO_EXTENSION);
}

//上传文件
function uploadFile()
{
if (!is_uploaded_file($this-&gt;tmpName)) {
exit("非法上传");
} else {
move_uploaded_file($this-&gt;tmpName,
//"upload/" . $_FILES["file"]["name"]);
$this-&gt;upDir . $this-&gt;upName .'.'. $this-&gt;getExtension($this-&gt;fileName));
echo "上传为: " . $this-&gt;upDir . $this-&gt;upName .'.'. $this-&gt;getExtension($this-&gt;fileName);
}
}
}
$up=new UploadFile();//上传图片
//$up=new UploadFile("file");//上传文件
?>
0

Deprecated: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in /www/wwwroot/testblog.58heshihu.com/var/Widget/Archive.php on line 1032

评论 (0)

取消