Skip to content

Instantly share code, notes, and snippets.

@palemoky
Created September 13, 2016 01:40
Show Gist options
  • Save palemoky/53db69821ad8bd22cb74b402b69f8e49 to your computer and use it in GitHub Desktop.
Save palemoky/53db69821ad8bd22cb74b402b69f8e49 to your computer and use it in GitHub Desktop.
单文件上传函数
<?php
function uploadFile($fileInfo,$uploadPath = 'uploads',$maxSize = (2<<20),$allowExt = array('jpg','png','jpeg','gif','bmp'),$checkImg=true){
$filename = $fileInfo['name'];
$type = $fileInfo['type'];
$tmp_name = $fileInfo['tmp_name'];
$size = $fileInfo['size'];
$error = $fileInfo['error'];
// $maxSize = (2<<20);//限制上传文件的大小为2M,以字节为单位
// $allowExt = array('jpg','png','jpeg','gif','bmp');
//判断错误号
if($error == 0){
//判断文件大小
if($size > $maxSize){
exit('亲,你的文件太大了,服务器放不下了呢~');
}
//判断文件类型
if(is_array($allowExt)){
$ext = pathinfo($filename,PATHINFO_EXTENSION);
if(!in_array($ext, $allowExt)){
exit('抱歉,该文件类型还不支持哦~');
}
}else{
exit('亲,文件类型参数好像有些不对:(');
}
//判断是否为真实图片类型
if($checkImg==true){
if(!getimagesize($tmp_name)){
exit('亲,你的图片好像有些问题:(');
}
}
//判断是否http post方式上传
if(!is_uploaded_file($tmp_name)){
exit('亲,请从正规渠道上传文件哦~');
}
//确保文件名唯一,防止重名覆盖
$uniName = md5(uniqid(microtime(true),true)).'.'.$ext;
//判断文件指定目录是否存在,不存在则创建
// $uploadPath = 'uploads';
if(!file_exists($uploadPath)){
mkdir($uploadPath,0777,true);
}
//将临时目录中的文件移动到指定位置
echo move_uploaded_file($tmp_name, $uploadPath.'/'.$uniName) ? 'Bingo! 文件传好了~' :'哦,文件上传失败,好像哪里出了点问题:(';
}else{
switch ($error) {
case 1:
$errMsg = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$errMsg = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。';
break;
case 3:
$errMsg = '文件只有部分被上传。';
break;
case 4:
$errMsg = '没有文件被上传。';
break;
case 6:
$errMsg = '找不到临时文件夹。';
break;
case 7:
$errMsg = '文件写入失败.';
break;
}
exit($errMsg);
}
}
uploadFile($_FILES['myFile']);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment