Code Security
 
Security Coding using PHP -- Write Safe Code
2. Prevention of File Upload Vulnerabilities
Questions
Question 1: How did the File Upload Vulnerabilities arise?
Question 2: Can we use only js not php to determine the file type?
Question 3: Why MUST use move_uploaded_file to handle file upload?
Units
A simple example of file upload
How did the File Upload Vulnerabilities arise
How to avoid the File Upload Vulnerabilities
1. A simple example of file upload
This is a simlpe file upload HTML code.
This is a simple PHP handle file upload code.
2. How did the File Upload Vulnerabilities arise
In the previous example, we did not do any determine on the type of the file uploaded. So user can upload a php file, then execute it from the brower, to perform his attack.
3. How to avoid the File Upload Vulnerabilities
1. Determine file type uploaded by JavaScript
2. Determine file type uploaded by PHP
3. Use move_uploaded_file to save the uploaded file safely
4. Add additional configurations to web server
3.1. Determine file type uploaded by JavaScript
At client side, determine the uploaded file type, and only allow specified file types to be uploaded.
3.2. Determine file type uploaded by PHP
After file is uploaded by client, determine the file type, and do not save file on the server if the file type is wrong.
3.3. Use move_uploaded_file to save the uploaded file safely
bool move_uploaded_file ( string $filename , string $destination )
This function checks to ensure that the file designated by from is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by to.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
3.4. Add additional configurations to web server
You can add additional configurations to web server to stop execute PHP files from the upload directory, so if JS or PHP determination are all bypassed for some reason, the attacker still cannot perform attack.
How to configure apache server not to execute php files:
 
Follow us at WeChat to get more info
Scan to use notes to record any inspiration
© 2024 Beijing Three Programmers Information Technology Co. Ltd  Terms  Privacy  Contact us  中文