PHP File Uploads
File uploads let users submit files to your server. Always validate file type, size, and name to prevent security vulnerabilities!
Output
Click Run to execute your code
$_FILES Array
| Key | Description |
|---|---|
$_FILES['file']['name'] |
Original filename |
$_FILES['file']['type'] |
MIME type |
$_FILES['file']['size'] |
File size in bytes |
$_FILES['file']['tmp_name'] |
Temporary location |
$_FILES['file']['error'] |
Error code (0 = success) |
Basic Upload
<?php
if (isset($_FILES['upload'])) {
$file = $_FILES['upload'];
if ($file['error'] === UPLOAD_ERR_OK) {
$destination = 'uploads/' . $file['name'];
move_uploaded_file($file['tmp_name'], $destination);
echo "File uploaded!";
}
}
?>
Validation
<?php
// Validate file type
$allowed = ['image/jpeg', 'image/png'];
if (!in_array($file['type'], $allowed)) {
die("Invalid file type");
}
// Validate size (5MB max)
if ($file['size'] > 5 * 1024 * 1024) {
die("File too large");
}
// Generate safe filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $extension;
?>
Summary
- $_FILES: Access uploaded files
- move_uploaded_file(): Save file
- Validate type: Check MIME type
- Validate size: Prevent huge files
- Generate filename: Use uniqid()
What's Next?
Congratulations! You've completed Module 8. Next, dive into File & Directory Operations!
Enjoying these tutorials?