您的位置:首页 > 编程语言 > PHP开发

PHP 单文件上传 only code

2015-05-05 23:19 411 查看
//封装单文件函数

$fileInfo = $_FILES ['myFile'];

//1.判断错误号

function uploadFile($fileInfo,$uploadPath = 'uploads',$flag = true,$allowExt = array ('jpeg', 'jpg', 'png', 'gif' ),$maxSize = 2097152) {

if ($fileInfo ['error'] > 0) {

switch ($fileInfo ['error']) {

case 1 :

$mes = '文件上传过大';

break;

case 2 :

$mes = '超过表单大小';

break;

case 3 :

$mes = '文件部分上传';

break;

case 4 :

$mes = '没有选择上传文件';

break;

case 6 :

$mes = '没有找到目录文件';

break;

case 7 :

case 8 :

$mes = '系统错误';

break;

}

exit ();

}

//2.检测文件上传类型

$ext = pathinfo ( $fileInfo ['name'], PATHINFO_EXTENSION );

//$allowExt = array ('jpeg', 'jpg', 'png', 'gif' );

if (! in_array ( $ext, $allowExt )) {

exit ( '文件非法' );

}

//3.检测文件大小

//$maxSize = 2097152;

if ($fileInfo ['szie'] > $maxSize) {

exit ( '文件过大' );

}

//检测图片是否真实

//$flag = true;

if($flag){

if(!getimagesize($fileInfo['tmp_name'])){

exit('文件格式不正确');

}

}

//4.是不是通过http post上传的

if (! is_uploaded_file ( $fileInfo ['tmp_name'] )) {

exit ( '文件不是通过https 文件上传的' );

}

//$uploadPath = 'uploads';

//文件不存在 创建

if (! file_exists ( $uploadPath )) {

mkdir ( $uploadPath, 0777, true );

chmod ( $uploadPath, 0777 );

}

$uniName = md5 ( uniqid ( microtime ( true ), true ) . '.' . $ext );

$destination = $uploadPath . '/' . $uniName;

if (! @move_uploaded_file ( $fileInfo ['tmp_name'], $destination )) {

exit ( '文件移动失败' );

}

return array(

'newName'=>$destination,

'size'=>$fileInfo['size'],

'type'=>$fileInfo['type']

);

}

//参考慕课网
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: