Editor's note (2026): The code in the original 2014 version of this tutorial was missing from the page. We've rewritten it with complete, working examples and added the security checks every upload script needs.
Image uploads are common on websites, whether for galleries, profile pictures, or product photos. In this tutorial we'll build a simple HTML form and a PHP script that saves the uploaded image to the server.
1. Create the form
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="photo">Upload a new profile picture:</label>
<input type="file" name="photo" id="photo" accept="image/*">
<button type="submit">Upload</button>
</form>
The form must use method="post" and enctype="multipart/form-data", or the file won't be sent.
2. Understand $_FILES
PHP puts uploaded files in the $_FILES array. For our field named photo:
$_FILES['photo']['name']— original file name$_FILES['photo']['type']— MIME type reported by the browser (don't trust it)$_FILES['photo']['size']— size in bytes$_FILES['photo']['error']— error code (UPLOAD_ERR_OKmeans success)$_FILES['photo']['tmp_name']— temporary location on the server
3. Create upload.php
<?php
$uploadDir = __DIR__ . '/images/userpics/';
$maxSize = 2 * 1024 * 1024; // 2 MB
$allowed = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
];
if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
exit('Upload failed. Please try again.');
}
if ($_FILES['photo']['size'] > $maxSize) {
exit('The file is too large (maximum 2 MB).');
}
// Check the real file type, not the browser-reported one
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['photo']['tmp_name']);
if (!isset($allowed[$mime])) {
exit('Only JPG, PNG, GIF, and WebP images are allowed.');
}
// Give the file a new, random name so users can't overwrite files
$newName = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadDir . $newName)) {
echo 'Your image was uploaded successfully.';
// Save $newName to your database here if needed (use prepared statements).
} else {
echo 'Could not save the file.';
}
The uploaded file first lands in a temporary location. move_uploaded_file() moves it to a permanent folder, here images/userpics/. Make sure that folder exists and is writable by the web server.
Security checklist
- Check the real file type with
finfo; never trust the file extension or browser type alone. - Limit file size (also set
upload_max_filesizeandpost_max_sizeinphp.ini). - Rename uploaded files; never use the user's file name directly.
- Prevent scripts from running in the upload folder (for example, with server configuration).
- If you store file details in a database, use prepared statements.
Need help building secure upload features for your website? I.T. For Less can help — contact us.