A set of web applications generally provide the file upload function to facilitate visitors to upload some files.
Below is a simple File Upload form
-
-
-
-
-
Php configuration file: php. ini. The option upload_max_filesize specifies the size of the file to be uploaded. The default value is 2 MB.
$ _ FILES array variable
PHP uses the variable $ _ FILES to upload FILES. $ _ FILES is an array. If test.txt is uploaded, the content of the $ _ FILES array is:
- $ FILES
- Array
- {
- [File] => Array
- {
- [Name] => test.txt // file name
- [Type] => text/plain // MIME type
- [Tmp_name] =>/tmp/php5D. tmp // temporary file
- [Error] => 0 // error message
- [Size] => 536 // file size, in bytes
- }
- }
If the name attribute value of the Upload file button is file
-
Use $ _ FILES ['file'] ['name'] to obtain the name of the uploaded file on the client, excluding the path. Use $ _ FILES ['file'] ['tmp _ name'] to obtain the temporary file path for the server to save the uploaded file.
Folder for storing uploaded files
PHP does not directly put the uploaded file in the root directory of the website, but saves it as a temporary file named $ _ FILES ['file'] ['tmp _ name, the developer must copy the temporary file to the saved website folder.
$ _ FILES ['file'] ['tmp _ name'] values are set by PHP, which is different from the original file name, developers must use $ _ FILES ['file'] ['name'] to obtain the original name of the uploaded file.
Error message during File Upload
$ _ FILES ['file'] ['error'] variable is used to save the error message during file upload. Its value is as follows:
Error Message |
Value |
Description |
UPLOAD_ERR_ OK |
0 |
No errors |
UPLOAD_ERR_INI_SIZE |
1 |
The size of the uploaded file exceeds the php. ini setting. |
UPLOAD_ERR_FROM_SIZE |
2 |
The size of the uploaded file exceeds the value of MAX_FILE_SIZE in the HTML form. |
UPLOAD_ERR_PARTIAL |
3 |
Upload only part of the file |
UPLOAD_ERR_NO_FILE |
4 |
No File Upload |
File Upload Vulnerability
If you provide the function for website visitors to upload images, you must be careful that the visitor may not actually upload images, but can specify a PHP program. If the directory where images are stored is an Open folder, intruders can remotely execute the uploaded PHP file to launch attacks.
The following is a simple File Upload example:
-
- // Set the directory of the uploaded file
- $ Uploaddir = "D:/www/images /";
- // Check whether the file exists
- If (isset ($ _ FILES ['file1'])
- {
- // Complete path to be put in the website directory, including the file name
- $ Uploadfile = $ uploaddir. $ _ FILES ['file1'] ['name'];
- // Move the path stored on the server to the actual file name
- Move_uploaded_file ($ _ FILES ['file1'] ['tmp _ name'], $ uploadfile );
- }
- ?>
- ......
-
-
-
-
-
This example does not check the file suffix and can upload any file. This is an obvious Upload Vulnerability.