php completes f...LOGIN

php completes file upload according to array and steps

The file content submitted by the form form points to file.php.

We process uploaded files through PHP code in file.php.

We choose a picture named to upload. Assume the name of the picture is: psu.jpg, click to upload.

PHP has prepared a dedicated system function $_FILES for file data. All related data of uploaded files are stored in this system function.

In the PHP file, we print $_FILES to observe the structure of this array:

<?php
//var_dump()或print_r()
//打印变量的相关信息,将变量的信息详细的展示出来
var_dump($_FILES);             
?>

The array structure of the printed result is as follows:

array (size=1)
    'file' => 
       array (size=5)
       //文件名
      'name' => string 'psu.jpg' (length=7) 
      //文件的mime类型
      'type' => string 'image/jpeg' (length=10)                    
      //缓存文件,上传的图片即保存在这里
      'tmp_name' => string 'E:\wamp\tmp\phpC32A.tmp' (length=23)
      //错误码,详见上面错误码介绍
      'error' => int 0                                             
      //上传的文件大小
      'size' => int 225824

We get the above Array structure.

We can start the file processing process.

The first step is to determine the error code:

<?php
if($_FILES['file']['error'] > 0){
   switch ($_FILES['file']['error']) {    //错误码不为0,即文件上传过程中出现了错误
       case '1':
           echo '文件过大';
           break;
       case '2':
           echo '文件超出指定大小';
           break;
       case '3':
           echo '只有部分文件被上传';
           break;
       case '4':
           echo '文件没有被上传';
           break;
       case '6':
           echo '找不到指定文件夹';
           break;
       case '7':
           echo '文件写入失败';
           break;
       default:
           echo "上传出错<br/>";
   }
}else{
   //错误码为0,即上传成功,可以进行后续处理,处理流程见下文
}
?>

The above code introduces the error code and corresponding error in detail. We can Error code to generate accurate error prompts.

The second step is to determine whether the file exceeds the size. In actual projects, due to system hardware limitations and storage device limitations, it is impossible for users to upload files without limit, so we have to limit the size of files uploaded by users. Defining an appropriate limit size can make our application run more stably.

<?php
//判断错误
if ($_FILES['file']['error'] > 0) {
    //有错误可停止执行
} else {
    //当前上传文件无误,运行本段代码
    //判断文件是否超出了指定的大小
    //单位为byte
    $MAX_FILE_SIZE = 100000;
    if ($_FILES['file']['size'] > $MAX_FILE_SIZE) {
        //判断,如果上传的文件,大小超出了我们给的限制范围,退上传并产生错误提示
        exit("文件超出指定大小");
    }
}
?>

Define the file size we specify as $MAX_FILE_SIZE. The counting unit of this variable is byte, which corresponds to the $_FILES['file']['size'] size of the uploaded file.
In the sample code, the limit is files with a size of approximately 100K and below.

The third step is to determine whether the mime type of the file is correct.

More often, our file upload function needs to determine whether the files uploaded by users meet the requirements. After uploading unavailable files, the overall display effect of the online application will be affected. , will cause adverse effects. So we need to use the mime type and suffix name to determine whether the file uploaded by the user meets the requirements.

In the following sample code, we assume that the current project requirement is to specify uploaded images, requiring the uploading of files with the suffix GIF or jpg. When the user uploads a file that does not meet the requirements, an error message is returned.

<?php
/*判断后缀名和MIME类型是否符合指定需求
例如:
当前项目指定上传后缀为.jpg或.gif的图片,则$allowSuffix = array('jpg','gif');
*/
//定义允许的后缀名数组
$myImg = explode('.', $_FILES['file']['name']);
/*
explode() 将一个字符串用指定的字符切割,并返回一个数组,这里我们将文件名用'.''切割,结果存在$myImg中,文件的后缀名即为数组的最后一个值
*/
$myImgSuffix = array_pop($myImg);
/*
根据上传文件名获取文件的后缀名
使用in_array()函数,判断上传文件是否符合要求
当文件后缀名不在我们允许的范围内时退出上传并返回错误信息
*/
if(!in_array($myImgSuffix, $allowSuffix)){
    exit("文件后缀名不符");
}
/*
mime类型和文件后缀名的对应关系,我们可以通过很多途径查询到,为了避免用户自主修改文件后缀名造成文件无法使用。
mime类型也必须做出限制检查mime类型,是为了防止上传者直接修改文件后缀名
导致文件不可用或上传的文件不符合要求。
*/
//数组内容为允许上传的mime类型
$allowMime = array(
    "image/jpg",
    "image/jpeg",
    "image/pjpeg",
    "image/gif"
);
if(!in_array($_FILES['file']['type'], $allowMime)){                      //判断上传文件的mime类型是否在允许的范围内
    exit('文件格式不正确,请检查');
    //如果不在允许范围内,退出上传并返回错误信息
}
?>

The fourth step is to generate the specified path and file name.

According to the file arrangement of the project, the file storage path is generated. In order to avoid errors caused by duplicate file names, a random file name is generated according to a certain format.

<?php
//指定上传文件夹
$path = "upload/images/";
/*
根据当前时间生成随机文件名,本行代码是使用当前时间 + 随机一个0-9的数字组合成文件名,后缀即为前面取到的文件后缀名
*/
$name = date('Y').date('m').date("d").date('H').date('i').date('s').rand(0,9).'.'.$myImgSuffix;
?>

The fifth step is to determine whether the file is uploaded.

The is_uploaded_file() function is a dedicated function to determine whether the target file is an uploaded file.

<?php

//使用is_uploaded_file()判断是否是上传文件,函数介绍见上文
if(is_uploaded_file($_FILEs['file']['tmp_name'])){    

}
?>

The sixth step is to move the file to the specified location.

Use the move_uploaded_file() function to move the file to the specified location and name it. It should be noted that the Linux system has permissions for the target directory and whether the disk space is sufficient, otherwise the upload operation will fail.

<?php
/*
使用move_uploaded_file()移动上传文件至指定位置,第一个参数为上传文件,第二个参数为我们在前面指定的上传路径和名称。
*/
if(move_uploaded_file($_FILEs['file']['tmp_name'], $path.$name)){
           //提示文件上传成功
           echo "上传成功";                                
       }else{
/*
文件移动失败,检查磁盘是否有足够的空间,或者linux类系统中文件夹是否有足够的操作权限
*/
           echo '上传失败';                                                
       }
   }else{
       echo '不是上传文件';
   }

}
?>

We organize this file fragment into a whole file:

<?php
if ($_FILES['file']['error'] > 0) {
   switch ($_FILES['file']['error']) {
       //错误码不为0,即文件上传过程中出现了错误
       case '1':
           echo '文件过大';
           break;
       case '2':
           echo '文件超出指定大小';
           break;
       case '3':
           echo '只有部分文件被上传';
           break;
       case '4':
           echo '文件没有被上传';
           break;
       case '6':
           echo '找不到指定文件夹';
           break;
       case '7':
           echo '文件写入失败';
           break;
       default:
           echo "上传出错<br/>";
   }
} else {

   $MAX_FILE_SIZE = 100000;
   if ($_FILES['file']['size'] > $MAX_FILE_SIZE) {
       exit("文件超出指定大小");

   }

   $allowSuffix = array(
       'jpg',
       'gif',
   );

   $myImg = explode('.', $_FILES['file']['name']);

   $myImgSuffix = array_pop($myImg);

   if (!in_array($myImgSuffix, $allowSuffix)) {
       exit("文件后缀名不符");
   }

   $allowMime = array(
       "image/jpg",
       "image/jpeg",
       "image/pjpeg",
       "image/gif",
   );

   if (!in_array($_FILES['file']['type'], $allowMime)) {
       exit('文件格式不正确,请检查');
   }

   $path = "upload/images/";
   $name = date('Y') . date('m') . date("d") . date('H') . date('i') . date('s') . rand(0, 9) . '.' . $myImgSuffix;

   if (is_uploaded_file($_FILEs['file']['tmp_name'])) {

       if (move_uploaded_file($_FILEs['file']['tmp_name'], $path . $name)) {
           echo "上传成功";
       } else {
           echo '上传失败';
       }

   } else {
       echo '不是上传文件';
   }

}
?>


Next Section
<?php if ($_FILES['file']['error'] > 0) { switch ($_FILES['file']['error']) { //错误码不为0,即文件上传过程中出现了错误 case '1': echo '文件过大'; break; case '2': echo '文件超出指定大小'; break; case '3': echo '只有部分文件被上传'; break; case '4': echo '文件没有被上传'; break; case '6': echo '找不到指定文件夹'; break; case '7': echo '文件写入失败'; break; default: echo "上传出错<br/>"; } } else { $MAX_FILE_SIZE = 100000; if ($_FILES['file']['size'] > $MAX_FILE_SIZE) { exit("文件超出指定大小"); } $allowSuffix = array( 'jpg', 'gif', ); $myImg = explode('.', $_FILES['file']['name']); $myImgSuffix = array_pop($myImg); if (!in_array($myImgSuffix, $allowSuffix)) { exit("文件后缀名不符"); } $allowMime = array( "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", ); if (!in_array($_FILES['file']['type'], $allowMime)) { exit('文件格式不正确,请检查'); } $path = "upload/images/"; $name = date('Y') . date('m') . date("d") . date('H') . date('i') . date('s') . rand(0, 9) . '.' . $myImgSuffix; if (is_uploaded_file($_FILEs['file']['tmp_name'])) { if (move_uploaded_file($_FILEs['file']['tmp_name'], $path . $name)) { echo "上传成功"; } else { echo '上传失败'; } } else { echo '不是上传文件'; } } ?>
submitReset Code
ChapterCourseware