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:
##Error code | Description |
Correct, you can continue with the subsequent operations of file upload. | |
2 | Exceeded the specified file size, specify the size limit for uploaded files according to the business needs of the project |
Only some files were uploaded |
Note★: There is no 5
## in the error code 2. Customize whether to judge whether File size range exceeded
##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 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.
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.
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.
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
PHP中文网
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:
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:
.
The first step is to determine the error code
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 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.
##
//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.
/*
For details, see example 1
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
##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.
Here is a simple upload page, and the form submits two files at the same time. We can submit content through this page.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.Upload picture programfor ($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
Program 1 html page
PHP中文网 Program 2
Submit to php page
* 1:超过了文件大小,在php.ini文件中设置Find one Upload pictures and see the program running results
* 2:超过了文件的大小MAX_FILE_SIZE选项指定的值
* 3:文件只有部分被上传
* 4:没有文件被上传
* 5:上传文件大小为0 */ $error=$upfile["error"];//上传后系统返回的值 echo "上传文件名称是:".$name."
"; echo "上传文件类型是:".$type."
"; echo "上传文件大小是:".$size."
"; echo "上传后系统返回的值是:".$error."
"; echo "上传文件的临时存放路径是:".$tmp_name."
"; echo "开始移动上传文件
"; //把上传的临时文件移动到指定目录下面 move_uploaded_file($tmp_name,'D:\upload/images/'.$name); $destination="D:\upload/images/".$name; echo "上传信息:
"; 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等格式的图片!"; } } ?>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 pageProgram 2 Submit to php pagePHP中文网 请选择要上传的文件
"; } } } ?>Run your program and take a lookExample 3
This example uploads a form and allows uploading files with a size of less than 1MBRun your program.0){ //判断文件大小 echo "上传成功"; }else{ echo "上传文件太大或未知"; } } ?>
- Course Recommendations
- Courseware download
![]()
IntermediateFront-end Vue3 actual combat [handwritten vue project]
2857 people are watching![]()
ElementaryAPIPOST tutorial [Popularization of technical concepts related to network communication]
1795 people are watching![]()
IntermediateIssue 22_Comprehensive actual combat
5521 people are watching![]()
ElementaryIssue 22_PHP Programming
5172 people are watching![]()
ElementaryIssue 22_Front-end development
8713 people are watching![]()
IntermediateBig data (MySQL) video tutorial full version
4525 people are watching![]()
ElementaryGo language tutorial-full of practical information and no nonsense
2794 people are watching![]()
ElementaryGO Language Core Programming Course
2814 people are watching![]()
IntermediateJS advanced and BootStrap learning
2563 people are watching![]()
IntermediateSQL optimization and troubleshooting (MySQL version)
3374 people are watching![]()
IntermediateRedis+MySQL database interview tutorial
2963 people are watching![]()
ElementaryDeliver food or learn programming?
5708 people are watchingThe 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
- Let's briefly talk about starting a business in PHP
- Quick introduction to web front-end development
- Large-scale practical Tianlongbabu development of Mini version MVC framework imitating the encyclopedia website of embarrassing things
- Getting Started with PHP Practical Development: PHP Quick Creation [Small Business Forum]
- Login verification and classic message board
- Computer network knowledge collection
- Quick Start Node.JS Full Version
- The front-end course that understands you best: HTML5/CSS3/ES6/NPM/Vue/...[Original]
- Write your own PHP MVC framework (40 chapters in depth/big details/must read for newbies to advance)
- About us Disclaimer Sitemap
- php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
The file was not uploaded | |
The temporary folder cannot be found, maybe the directory does not exist or does not have permissions | |
Failed to write the file, maybe the disk is full or does not have permissions |