/**
* 读取文件头部判断文件准确类型
*/
class UpLoader{
private $path;
private $files;
private $checkFunction;
/**
* @param $allow_type 接受参数为过滤类型,目前有"images"和"zip"两种,可以扩展
*/
function UpLoader($allow_type){
$this->path = getenv('SINASRV_CACHE_DIR').'zhuanqu_files/';
switch($allow_type){
case 'image':
$this->checkFunction = 'checkIfImage';
break;
case 'zip':
$this->checkFunction = 'checkIfZip';
break;
}
}
/**
* 执行上传
* @param $files 参数为$_FILES数组
*/
public function doUpload($files){
$this->files = $files;
$func = $this->checkFunction;
if($this->files['files']['name'] != '' && $this->files['files']['error'] == UPLOAD_ERR_OK) {
$tmp_name = $this->files["files"]["tmp_name"];
//检查文件类型
if( $this->$func($tmp_name) ){
$name = md5_file($tmp_name);
$name = $name.'___'.$this->files["files"]["name"];
if(move_uploaded_file($tmp_name, $this->path.$name)){
echo '<script> alert("上传成功!"); </script>';
}
}
}
}
private function checkIfImage($fileName){
$file = fopen($fileName, "rb");
$bin = fread($file, 2); //只读2字节
fclose($file);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
if($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/) {
return true;
}else{
echo '<script> alert("仅允许上传jpg/gif/png格式的图片!"); </script>';
return false;
}
}
private function checkIfZip($fileName){
$file = fopen($fileName, "rb");
$bin = fread($file, 2); //只读2字节
fclose($file);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
if($typeCode == 8075) {
return true;
}else{
echo '<script> alert("仅允许上传zip格式的文件!"); </script>';
return false;
}
}
}