PHP文件上传函数封装 ?php function uploadFile( $fileInfo, $uploadPath = './attachment', $flag = true, $allowExt = ['jpg', 'png', 'wbmp', 'gif', 'jpeg', 'bmp'], $maxSize = 2097152 ) { if ( $fileInfo['error'] == 0 ) { $arr = explode( '
PHP文件上传函数封装
-
<?php -
function uploadFile( $fileInfo, $uploadPath = './attachment', $flag = true, $allowExt = ['jpg', 'png', 'wbmp', 'gif', 'jpeg', 'bmp'], $maxSize = 2097152 ) { -
if ( $fileInfo['error'] == 0 ) { -
$arr = explode( '.', $fileInfo['name'] ); -
//explode 分割字符串,以.点分割 -
$ext = end( $arr ); -
//取后缀名 -
$prefix = array_shift( $arr ); -
//取文件名 -
if ( !in_array( $ext, $allowExt ) ) { -
//判断后缀是否存在 -
return $res = '文件类型不合法'; -
} -
if ( $fileInfo['size'] > $maxSize ) { -
//判断文件大小 -
return $res = '文件大小超过限制的最大值'; -
} -
if ( !getimageSize( $fileInfo['tmp_name'] ) ) { -
//检测图片是否合法 -
return $res = '请勿上传非法图片'; -
} -
if ( !is_uploaded_file( $fileInfo['tmp_name'] ) ) { -
//检测上传方式是否为http post -
return $res = '上传方式错误:请使用http post 方式上传'; -
} -
//定义存储文件目录, 按年月规类存放 -
$uploadPath = $uploadPath . '/' . date( 'Y' ) . '/' . date( 'm' ) ; -
if ( !file_exists( $uploadPath ) ) { -
//file_exists判断目录是否存在 -
mkdir( $uploadPath, 0770, true ); -
//mkdir创建目录,参数0770为权限 -
chmod( $uploadPath, 0770 ); -
//为以防万一,再次修改权限为0770 -
} -
$des = $uploadPath . '/'.md5( $prefix.time() ).'.'.$ext; -
//将散列后的文件名,与后缀拼接。( $prefix.time()拼接为原文件名+时间戳,md5 在将其散列形成独一无二的文件名,避免用户上传相同文件名的文件导致出现问题 ) -
// echo $des; -
//调试用 -
$moveResult = move_uploaded_file( $fileInfo['tmp_name'], $des ); -
//参数:将$fileInfo['tmp_name']临时文件,复制到$des, -
if ( !$moveResult ) { -
$res['error'] = '文件移动失败'; -
} else { -
$res['info'] = $fileInfo['name'] . '上传成功'; -
$res['fileRealPath'] = $des; -
} -
return $res; -
} else { -
switch( $fileInfo['error'] ): -
case 1: -
echo '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值'; -
break; -
case 2: -
echo '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值'; -
break; -
case 3: -
echo '文件只有部分被上传'; -
break; -
case 4: -
echo '没有文件被上传。 是指表单的file域没有内容,是空字符串'; -
break; -
case 6: -
echo '找不到临时文件夹'; -
break; -
default: -
echo '系统错误'; -
endswitch; -
} -
}
上传表单
-
<!DOCTYPE html> -
<html lang="en"> -
<head> -
<meta charset="UTF-8" /> -
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> -
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> -
<title>文件上传</title> -
</head> -
<body> -
<form -
action="uploadhttp://img.558idc.com/uploadfile.php" -
method="post" -
enctype="multipart/form-data" -
> -
<fieldset> -
<legend>文件上传</legend> -
<label for="my_file"></label> -
<input type="file" name="my_file" id="my_file" /> -
<button>上传</button> -
</fieldset> -
</form> -
</body> -
</html>
成功上传文件,并按年/月分类存放

