PHP File Upload
In this page:
The $_FILES Array
When a file is uploaded to your server through an HTML form, PHP stores all information about that file inside the $_FILES superglobal array, including its original name, MIME type, size, and temporary server location.
Example: The $_FILES Array
<?php
$_FILES['photo'] = [
'name' => 'profile.jpg',
'type' => 'image/jpeg',
'size' => 24576,
'tmp_name' => '/tmp/phpXXXXXX',
];
echo $_FILES['photo']['name'] . " (" . $_FILES['photo']['type'] . ")";
?>
Login to try C/C++/Java/PHP code in the editor
Moving Uploaded Files
Files are initially placed in a temporary folder on the server. To keep them permanently, you must move them to your target directory using move_uploaded_file(), which also verifies the file genuinely came from an HTTP upload.
Example: Moving Uploaded Files
<?php
// Simulated for demonstration -- in real use, $_FILES['photo']['tmp_name'] comes from an actual upload
$tmpPath = "data.txt";
file_put_contents($tmpPath, "uploaded content");
$destination = "uploads/photo.txt";
echo "Would move $tmpPath to $destination via move_uploaded_file()";
?>
Login to try C/C++/Java/PHP code in the editor
Verifying File Types
Never trust the file extension or MIME type reported by the browser, since both are easy to spoof — validate the actual file contents (for example, checking image files with getimagesize()) before treating an upload as safe.
Example: Verifying File Types
<?php
$_FILES['photo']['name'] = "photo.jpg.php"; // spoofed extension
$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
echo "Reported extension: $ext -- never trust this alone, verify contents instead";
?>
Login to try C/C++/Java/PHP code in the editor
Restricting File Size
Uploading very large files can consume server space and memory, so always check the size key in $_FILES against your project's limits, and make sure your php.ini upload_max_filesize setting matches your intended limit too.
Example: Restricting File Size
<?php
$_FILES['photo']['size'] = 5000000;
$maxSize = 2000000;
if ($_FILES['photo']['size'] > $maxSize) {
echo "File too large";
} else {
echo "File size OK";
}
?>
Login to try C/C++/Java/PHP code in the editor
Handling Upload Errors
The error key inside $_FILES holds a numeric error code — 0 (UPLOAD_ERR_OK) means success, while other values point to specific problems like exceeding the size limits configured in php.ini.
Example: Handling Upload Errors
<?php
$_FILES['photo']['error'] = UPLOAD_ERR_OK;
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
echo "Upload succeeded";
} else {
echo "Upload failed with error code " . $_FILES['photo']['error'];
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: