Forms & User Input · Lesson 6 of 6
File Uploads
Validate uploaded files and store them outside executable web paths.
Lesson
Uploads arrive through $_FILES and must be checked for upload errors, size, and actual file type. Never trust the client-provided filename or MIME type. Generate a server-side name, use is_uploaded_file and move_uploaded_file, and store files where the web server cannot execute them.
This example shows the required upload check before a file is moved; production code must also enforce size and an allowlist of detected types.
Further guidance
Treat every submitted field and uploaded file as untrusted. Validate type, length, allowed values, and request method on the server; use CSRF protection for state changes. Escape values for their output context, and never use browser validation as the only safeguard.
Practice task: Create a fresh example for File Uploads. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
File Uploads
PHP
$file = $_FILES['document'] ?? null;
if (is_array($file) && $file['error'] === UPLOAD_ERR_OK && is_uploaded_file($file['tmp_name'])) {
echo 'Upload received; validate type and size before storing.';
}
Expected output
Upload received after a successful HTTP upload
Key points
- Validate uploaded files and store them outside executable web paths.
- Validate input on the server before processing it.
- Escape output for its context and protect state-changing forms from CSRF.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.