PHP file uploadLOGIN

PHP file upload

To successfully implement the upload function, you must first enable file upload in php.ini and make reasonable settings for some parameters. Find the File Upload item and you can see that there are three attributes below, with the following meanings.

file_upload: If the value is on, it means that the server supports file upload. Otherwise, vice versa

upload_tmp_dir: Temporary directory for uploading files. Before the file is successfully uploaded, the file is first stored in the server's temporary directory. If you want to know the location, you can set the storage path later, otherwise, use the system default directory

upload_max_filesize: The maximum size of files allowed to be uploaded by the server, in MB. The system default is 2MB, users can set it by themselves

★ If you use the integrated installation package to configure the PHP development environment, the configuration information introduced above has been configured by default.


File upload steps

For better learning PHP, we have summarized the complex PHP file upload into 6 steps.

In actual use, you can successfully complete PHP file upload by following these 6 steps:

1. Determine whether there is an error code

Detailed error code returned by the system:


0 Correct, you can continue with the subsequent operations of file upload. Exceeds the maximum limit of uploaded files, upload_max_filesize = 2M is set in php.ini, The general default is 2M. It can be modified according to the actual needs of the project ## 3Only some files were uploaded
##Error code Description


1

2

Exceeded the specified file size, specify the size limit for uploaded files according to the business needs of the project
4The file was not uploaded 6The temporary folder cannot be found, maybe the directory does not exist or does not have permissions 7Failed to write the file, maybe the disk is full or does not have permissions

Note★: There is no 5


## in the error code 2. Customize whether to judge whether File size range exceeded

#While developing the upload function. As developers, we, in addition to the maximum upload value specified in php.ini.

We usually also set a value, which is the upload size limit specified by the business.

For example:

Sina Weibo or QQ Zone only allows a single avatar picture of 2M. When uploading albums, you can upload more than 2M.

So, its system supports larger file uploads.

The judgment file size here is used to limit the uploaded file size we want to specify in actual business.


##3. Determine whether the suffix name and MIME type match

##MIME (Multipurpose Internet Mail Extensions) is a multipurpose Internet mail extension type. It is a type of method that sets a file with a certain extension to be opened by an application. When the file with the extension is accessed, the browser will automatically use the specified application to open it. It is mostly used to specify some client-defined file names and some media file opening methods.

When determining the suffix and MIME type, we will use a PHP function in_array(), which passes in two parameters.

The first parameter is the value to be judged;

The second parameter is the range array.


We use this function to determine whether the file extension and mime type are within the allowed range.

# 4. Generate file name



Our file was uploaded successfully, but it will not be saved with its original name.

Because some people who have sensitive keywords in their original names will violate the relevant laws and regulations of our country.

We can use date(), mt_rand() or unique() to generate random file names.


5. Determine whether the file is uploaded.


Our file was uploaded successfully, but it will not be saved with its original name. Because some people who have sensitive keywords in their original names will violate the relevant laws and regulations of our country.

We can use date(), mt_rand() or unique() to generate random file names. When the file upload is successful, the system will upload the uploaded temporary file to the system's temporary directory. Create a temporary file.

At the same time, a temporary file name will be generated. What we need to do is move the temporary files to the specified directory on the system.

It is unscientific not to move blindly before moving, or to move wrongly. Before moving, we need to use relevant functions to determine whether the uploaded file is a temporary file.

is_uploaded_file() passes in a parameter (the cache file name in $_FILES) to determine whether the passed in name is an uploaded file.


6. Move temporary files to the specified directory

Temporary files are real temporary files, we need to move them to our under the website directory.

Let others access the data in our website directory.

We use: move_uploaded_file().
This function moves the uploaded file to the specified location and names it.
Pass in two parameters:
The first parameter is the uploaded file that specifies the move;
The second parameter is the string concatenating the specified folder and name.

To upload files, a form must be prepared on the web page. Just like the following

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>PHP中文网</title>
 </head>
 <body>
 
 <form action="file.php" method="post" enctype="multipart/form-data">
     <input type="file" name="file">
     <input type="submit" value="上传">
 </form>
 
 </body>
 </html>

Notes:

1. The parameter method in the form form must be post. If it is get, file upload cannot be performed

2. The enctype must be multipart/form-dat

3. When type=file is selected, the default is to upload the file content.

The file content submitted by the above 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: .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);
?>

Program running results:

array(1) {
["file"]=>
array(5) {
["name"]=>
string(7) "psu.jpg"
["type"]=> ;
string(10) "image/jpeg"
["tmp_name"]=>
string(22) "C:\Windows\phpE2F1.tmp"
["error"]= >
int(0)
["size"]=>
int(488929)
}
}

##The array structure of the printed result is as follows:

array (size=1)
'file' =>
array (size=5)
//File name
'name' => string 'psu.jpg' (length=7)
//The mime type of the file
'type' => string 'image/jpeg' (length=10)


// Cache files, uploaded pictures are saved here
'tmp_name' => string 'E:\wamp\tmp\phpC32A.tmp' (length=23)
//Error code, see the error code above for details Introduction
'error' => int 0 'size' => int 225824


The above array structure is obtained.

We can start the file processing process

.


The first step is to determine the error code

<?php
header("Content-type:text/html;charset=utf-8");
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{
    echo "上传成功";//错误码为0,即上传成功,可以进行后续处理,处理流程见下文
}
?>

Detailed introduction to the above code Knowing the error code and corresponding error, we can generate accurate error prompts based on the error code.


#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 restrictions, so we have to impose restrictions on users Limit the size of uploaded files. Defining an appropriate limit size can

#our application run more stably.

<?php
header("Content-type:text/html;charset=utf-8");
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 pass

Use the mime type and suffix name to determine whether the file uploaded by the user meets the requirements.

In the example code below, 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. .

/*Determine whether the suffix name and MIME type meet the specified requirements

For example:
The current project specifies to upload images with the suffix .jpg or .gif, then $allowSuffix = array ('jpg','gif');
*/


//Define the allowed suffix name array
$myImg = explode('.', $_FILES['file' ] ['name']);

/*
Explode () to cut a string in a specified character and return a array. Here we cut the file name in '. Stored in $myImg, the suffix name of the file is the last value of the array
*/


$myImgSuffix = array_pop($myImg);

/*
Get the suffix name of the file based on the uploaded file name
Use the in_array() function to determine whether the uploaded file meets the requirements
When the file suffix name is not within our allowed range, exit the upload and return an error message
*/

if(!in_array($myImgSuffix, $allowSuffix)){ We can query the corresponding relationship of suffix names through many ways. In order to prevent users from modifying file suffix names independently and causing the file to become unusable.
The mime type must also be restricted to check the mime type in order to prevent the uploader from directly modifying the file suffix
causing the file to become unavailable or the uploaded file does not meet the requirements.
*/

//The content of the array is the mime type that is allowed to be uploaded
$allowMime = array(
“image/jpg”,
“image/jpeg”,
"image/pjpeg",
"image/gif"
);


if(!in_array($_FILES['file']['type'], $allowMime)) { #}


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.

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.

//Specify the upload folder
$path = "upload/images/";

/*
Generate a random file name based on the current time, this line of code It uses the current time + a random number from 0 to 9 to form a file name, and the suffix is ​​the file suffix obtained previously
*/

$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
//Use is_uploaded_file() to determine whether it is an uploaded file. For function introduction, see above
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.

/*
Use move_uploaded_file() to move the uploaded file to the specified location. The first parameter is the uploaded file, and the second parameter is the upload path and name we specified previously.
*/

if(move_uploaded_file($_FILEs['file']['tmp_name'], $path.$name)){
                                                                                                                                                                             
Upload successful";              
                                                                                                                                                                                                                             {
              echo 'Not an uploaded file';
  }
 
}
?>



We organize this file fragment into a whole file: A simple program to upload pictures

For details, see example 1

##Multiple file upload


Introduces the process of uploading a single file in PHP. But sometimes, for convenience, we need to meet the need to upload multiple files at the same time. The principle of multi-file upload is the same, but when processing data, the uploaded data needs to be specially processed.

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>PHP中文网</title>
 </head>
 <body>
 <html>
 <body>
 <form action="morefile.php" method="post" enctype="multipart/form-data">
     <input type="file" name="file[]">
     <input type="file" name="file[]">
     <input type="submit" value="上传">
 </form>
 </body>
 </html>
 </body>
 </html>
Here is a simple upload page, and the form submits two files at the same time. We can submit content through this page.

Note:

1. Input type="file" name="file[]"compared with before, an extra square bracket is added after file

2.  Write 2 or more input type="file" name="file[]" The array structure is as follows

array (size=1)
'file' =>
array (size=5)
'name' =>
array (size=2)
            //File name
                                                                                                                                                                                                                                                                                       
                                                                                      =>
//Cache file
'tmp_name' =>
                                                                                                                                                                                                                                                                                                      . )
0 => int 0
1 => int 0
//File size
'size' =>
array (size=2)
0 => int 225824 Therefore, we need to use a for() loop to retrieve the required data from the two files respectively.

The data of two files are saved in $_FILES at the same time. We need to use a simple loop to read the information of a single file and move the file to the location we want to put.

for ($i=0; $i < count($_FILE['file']['name']); $i++) {

/*
Use is_uploaded_file () The function determines that the file is uploaded
and there is no error
*/

if(is_uploaded_file($_FILEs['file']['tmp_name'][$i]) && $_FILEs[ 'file']['error'][$i] == 0){ ​​​'file']['name'][$i])){
//Use the move_uploaded_file() function to move the file to the specified location and use the original name of the file
echo "Upload successful";

                                                                                                        ‐                                                    ’ ‐ ‐ echo 'upping‐failed''‐‐‐‐‐‐‐ of }

}



For the detailed judgment process, see single file upload. Only basic judgment is made here, and there is no reminder about the file size and format.




Example 1


Upload picture program


Program 1 html page

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>PHP中文网</title>
 </head>
 <body>
 
 
 <form action="file-upload.php" enctype="multipart/form-data" method="post" name="uploadfile">
     上传文件:<input type="file" name="upfile" /><br>
     <input type="submit" value="上传" /></form>
 </form>
 
 </body>
 </html>

Program 2
Submit to php page

<?php
 header("Content-type:text/html;charset=utf-8");
 //print_r($_FILES["upfile"]); 
 if(is_uploaded_file($_FILES['upfile']['tmp_name'])){
     $upfile=$_FILES["upfile"];
 //获取数组里面的值 
     $name=$upfile["name"];//上传文件的文件名
     $type=$upfile["type"];//上传文件的类型
     $size=$upfile["size"];//上传文件的大小
     $tmp_name=$upfile["tmp_name"];//上传文件的临时存放路径
 //判断是否为图片 
     switch ($type){
         case 'image/pjpeg':$okType=true;
             break;
         case 'image/jpeg':$okType=true;
             break;
         case 'image/gif':$okType=true;
             break;
         case 'image/png':$okType=true;
             break;
     }
 
     if($okType){
         /**
          * 0:文件上传成功<br/>
          * 1:超过了文件大小,在php.ini文件中设置<br/>
          * 2:超过了文件的大小MAX_FILE_SIZE选项指定的值<br/>
          * 3:文件只有部分被上传<br/>
          * 4:没有文件被上传<br/>
          * 5:上传文件大小为0
          */
         $error=$upfile["error"];//上传后系统返回的值
         echo "上传文件名称是:".$name."<br/>";
         echo "上传文件类型是:".$type."<br/>";
         echo "上传文件大小是:".$size."<br/>";
         echo "上传后系统返回的值是:".$error."<br/>";
         echo "上传文件的临时存放路径是:".$tmp_name."<br/>";
 
         echo "开始移动上传文件<br/>";
 //把上传的临时文件移动到指定目录下面
         move_uploaded_file($tmp_name,'D:\upload/images/'.$name);
         $destination="D:\upload/images/".$name;
 
         echo "上传信息:<br/>";
         if($error==0){
             echo "文件上传成功啦!";
 
         }elseif ($error==1){
             echo "超过了文件大小,在php.ini文件中设置";
         }elseif ($error==2){
             echo "超过了文件的大小MAX_FILE_SIZE选项指定的值";
         }elseif ($error==3){
             echo "文件只有部分被上传";
         }elseif ($error==4){
             echo "没有文件被上传";
         }else{
             echo "上传文件大小为0";
         }
     }else{
         echo "请上传jpg,gif,png等格式的图片!";
     }
 }
 ?>
Find one Upload pictures and see the program running results

Example 2

This example has 4 file upload domains. The name of the domain is u_file[], and the file information uploaded after submission is saved to $_FILES[u_file] to generate a multi-dimensional array. Read the array information and upload the file.


Program 1 html page

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>PHP中文网</title>
 </head>
 <body>
 <html>
 <body>
 <p>请选择要上传的文件</p>
 <form action="morefile.php" method="post" enctype="multipart/form-data">
   <table border="1" bgcolor="f0f0f0">
       <tr>
           <td>上传文件</td>
           <td><input type="file" name="u_file[]"></td>
       </tr>
       <tr>
           <td>上传文件</td>
           <td><input type="file" name="u_file[]"></td>
       </tr>
       <tr>
           <td>上传文件</td>
           <td><input type="file" name="u_file[]"></td>
       </tr>
       <tr>
           <td>上传文件</td>
           <td><input type="file" name="u_file[]"></td>
       </tr>
       <tr>
           <td colspan="2"><input type="submit" value="上传"></td>
       </tr>
 
   </table>
 </form>
 </body>
 </html>
 </body>
 </html>
Program 2 Submit to php page
<?php
header("Content-type:text/html;charset=utf-8");
if(!empty($_FILES[u_file][name])){           //判断遍历$_FILES是否为空
    $file_name=$_FILES[u_file][name];         //将上传文件名另存为数组
    $file_tmp_name=$_FILES[u_file][tmp_name];      //将上传的临时文件名另存为数组
    for($i=0;$i<count($file_name);$i++){         //循环上传文件
        if($file_name[$i]!=""){                 //判断上传文件名是否为空
            move_uploaded_file($file_tmp_name[$i],$i.$file_name[$i]);
            echo "文件" .$file_name[$i] ."上传成功。更名为"."$file_name[$i]"."<br>";
        }
    }
}
?>
Run your program and take a look

Example 3


This example uploads a form and allows uploading files with a size of less than 1MB

<from action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</from>
<?php
if(!empty($_FILES[file][name])){      //判断是否有文件上传
    $fileinfo=$_FILES[file];         //将文件信息赋给变量$fileinfo
    if($fileinfo['size']<1000000 && $fileinfo['size']>0){         //判断文件大小
        echo "上传成功";
    }else{
        echo "上传文件太大或未知";
    }
}
?>
Run your program.

Next Section

<from action="" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </from> <?php if(!empty($_FILES[file][name])){ //判断是否有文件上传 $fileinfo=$_FILES[file]; //将文件信息赋给变量$fileinfo if($fileinfo['size']<1000000 && $fileinfo['size']>0){ //判断文件大小 echo "上传成功"; }else{ echo "上传文件太大或未知"; } } ?>
submitReset Code
ChapterCourseware
    None