选择文件,进行判断,并将文件传入到指定文件夹
<?php
header('Content-type:text/html;charset=utf-8');
/*
*实现文件上传
*$param1 array $file
*$param2 aray $allow_type 允许上传的MIME类型
*$param3 string $path 存储路径
*$param4 string $error 出错原因
*$param5 array &allow_format = array() 允许上传文件格式
*$param6 int $max_sixe = 2000000 允许上传最大值
*/
function upload_single(
$file,
$allow_type,
$path,
$error,
$allow_format = array(),
$max_size = 2000000
) {
//判断文件是否有效
if (!is_array($file) || !isset($file['error'])) {
$error = '这不是一个有效的文件';
echo $error;
return false;
}
//判断文件上传路径
if (!is_dir($path)) {
//路径不存在
$error = '文件存储路径不存在';
echo $error;
return false;
}
//判断文件上传是否出错
switch ($file['error']) {
case 1:
case 2:
$error = '文件超出服务器大小';
echo $error;
return false;
case 3:
$error = '文件长传出现问题';
echo $error;
case 4:
$error = '用户没选择上传文件';
echo $error;
case 6:
case 7:
$error = '文件保存失败';
echo $error;
return false;
}
//判断文件类型
if (!in_array($file['type'],$allow_type)){
//该文件不能上传
$error = '当前文件不允许';
return false;
}
//判断后缀是否允许
//取出后缀
$ext = ltrim(strchr($file['name'],'.'),'.');
if (!empty($allow_format) && !in_array($ext,$allow_format)){
//不允许上传
$error = '当前文件格式不允许上传';
echo $error;
return false;
}
//判断当前文件大小是否满足当前需求
if ($file['size']>$max_size){
//文件过大
$error = '当前文件过大' . $max_size . '字节';
echo $error;
}
//构造文件名字:类型:年月日+随机字符串.$ext
$fullname = strstr($file['type'],'/',TRUE).date("Y-m-d");
for ($i = 0;$i<4;$i++){
$fullname .= chr(mt_rand(65,90));
}
$fullname .='.' . $ext;
//移到指定目录
if (!is_uploaded_file($file['tmp_name'])){
//上传文件
//move_uploaded_file($file['tmp_name'],'uploads/' . $file['name']);
//不是上传文件
$error = '错误:不是上传到指定文件';
return false;
}
if (move_uploaded_file($file['tmp_name'],$path.'/'.$fullname)){
//成功
return $fullname;
}else{
$error = '错误:文件上传失败';
return false;
}
}
//提供数据
$file=$_FILES['image'];
$path='uploads/';
$allow_type=array('image/jpg','image/jpeg','image/gif','image/png','image/');
$allow_format=array('jpg','jpeg','gif','png');
$max_size = 800000000;
$error=" 重新选择";
//调用函数
if ($filename = upload_single($file,$allow_type,$path,$error,$allow_format,$max_size)){
echo $filename;
}else{
echo $error;
}