请根据自己需要进行调整🤪
文件格式验证
function check_upload_file($filesTag = 'file', $suffix_array = array('jpg', 'jpeg', 'png'), $max_size = 10, $min_size = 0.001){
$max_size = 1024 * 1024 * $max_size;
$min_size = 1024 * 1024 * $min_size;
$file_name = $_FILES[$filesTag]['name'];
$file_size = $_FILES[$filesTag]['size'];
$tmp_name = $_FILES[$filesTag]['tmp_name'];
if (@is_uploaded_file($tmp_name) === false) setBreakDesc(5000, array(), '上传文件来源错误');
if (!$file_name) setBreakDesc(5000, array(), '请上传文件');
$suffix = getFileSuffix($file_name);
if (in_array($suffix, $suffix_array) === false) setBreakDesc(5000, array(), '请上传正确格式的文件');
if ((string)$file_size > (string)$max_size) setBreakDesc(5000, array(), '上传文件大小超过限制');
if ((string)$file_size < (string)$min_size) setBreakDesc(5000, array(), '上传文件太小');
$response['file_name'] = $file_name;
return $response;
}
文件上传
function upload_file($upload_path = "", $filesTag = 'file'){
if (empty($upload_path)) setBreakDesc(5000, array(), '请确认上传路径');
$file_name = $_FILES[$filesTag]['name'];
$suffix = getFileSuffix($file_name);
$tmp_name = $_FILES[$filesTag]['tmp_name'];
if (!file_exists($upload_path)) mkdir($upload_path, 0755, true);
if (@is_writable($upload_path) === false) setBreakDesc(5000, array(), '上传目录没有权限');
$upload_file_name = date("His") . '_'.md5(uniqid()).'_' . rand(10000, 99999) . ".{$suffix}";
$file_path = $upload_path . "{$upload_file_name}";
if (move_uploaded_file($tmp_name, $file_path) === false) setBreakDesc(5000, array(), '上传文件失败');
chmod($file_path, 0644);
clearstatcache();
return $upload_file_name;
}
公共状态码
return array(
'response_code' => array(
1000=>'执行成功',
5000=>'执行失败',
)
);
公共方法
function getFileSuffix($str){
$suffix = explode(".",$str);
return strtolower(end($suffix));
}
function setBreakDesc($code = 5000, $data = array(), $msg = '')
{
$status['code'] = $code;
$status['msg'] = empty($msg) ? C('response_code')[$code] : $msg;
if (!empty($data)) $status['result'] = $data;
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($status,JSON_UNESCAPED_UNICODE));
}
|