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:
##Error code
Description
0
Correct, you can continue with the subsequent operations of file upload.
1
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
2
Exceeded the specified file size, specify the size limit for uploaded files according to the business needs of the project
## 3
Only some files were uploaded
4
The file was not uploaded
6
The temporary folder cannot be found, maybe the directory does not exist or does not have permissions
7
Failed 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
##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
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" );
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 */
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. */
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.
=> //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.
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
The courseware is not available for download at the moment. The staff is currently organizing it. Please pay more attention to this course in the future~
Students who have watched this course are also learning