Introduction
In PHP, file uploads allow users to send images, documents, and other files to a website. PHP receives these files through the $_FILES superglobal. In this chapter, you will learn how to upload files, check file size and type, validate extensions, handle upload errors, and save files safely on a server. File Uploads and Validation in PHP Practice Questions with Solutions to help you to understand the concepts.
Question 1: Upload a File Using PHP
Problem Statement
Create a PHP program that allows a user to upload a file and saves it inside an uploads folder.
PHP Solution
upload.php
<!DOCTYPE html>
<html>
<body>
<form method="POST" enctype="multipart/form-data">
Select File:
<input type="file" name="myfile">
<button type="submit" name="upload">Upload File</button>
</form>
<?php
if (isset($_POST["upload"])) {
if (
isset($_FILES["myfile"]) &&
$_FILES["myfile"]["error"] === UPLOAD_ERR_OK
) {
$uploadDir = "uploads/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$fileName = bin2hex(random_bytes(16));
$destination = $uploadDir . $fileName;
if (move_uploaded_file(
$_FILES["myfile"]["tmp_name"],
$destination
)) {
echo "File uploaded successfully.";
} else {
echo "File upload failed.";
}
} else {
echo "Please select a valid file.";
}
}
?>
</body>
</html>
Sample Output
File uploaded successfully.
Explanation
enctype="multipart/form-data"allows the form to send files.$_FILES["myfile"]contains information about the uploaded file.tmp_namecontains the temporary location of the uploaded file.move_uploaded_file()moves the uploaded file to the destination.random_bytes()generates a random file name to avoid using the original filename.
Concepts Covered
- PHP file uploads
$_FILESmultipart/form-datamove_uploaded_file()- Creating upload directories
Question 2: Check File Upload Errors
Problem Statement
Create a PHP program that checks whether a file was uploaded successfully. Display an appropriate message if the upload fails.
PHP Solution
<?php
if (isset($_FILES["document"])) {
$file = $_FILES["document"];
switch ($file["error"]) {
case UPLOAD_ERR_OK:
echo "File uploaded successfully.";
break;
case UPLOAD_ERR_NO_FILE:
echo "No file was selected.";
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
echo "File size exceeds the allowed limit.";
break;
case UPLOAD_ERR_PARTIAL:
echo "File was only partially uploaded.";
break;
default:
echo "An error occurred during file upload.";
}
}
?>
Sample Output
When no file is selected:
No file was selected.
When a file uploads successfully:
File uploaded successfully.
Explanation
PHP provides predefined upload error codes.
| Error Constant | Meaning |
|---|---|
UPLOAD_ERR_OK | File uploaded successfully |
UPLOAD_ERR_NO_FILE | No file was selected |
UPLOAD_ERR_INI_SIZE | File exceeds the PHP upload limit |
UPLOAD_ERR_FORM_SIZE | File exceeds the form’s specified limit |
UPLOAD_ERR_PARTIAL | File was only partially uploaded |
The switch statement checks the error code and displays the appropriate message.
Concepts Covered
- File upload errors
$_FILES["document"]["error"]- Upload error constants
- Switch statement
Question 3: Validate File Size Before Uploading
Problem Statement
Create a PHP program that allows a user to upload a file only if its size is less than or equal to 2 MB.
PHP Solution
<?php
if (isset($_FILES["myfile"])) {
$file = $_FILES["myfile"];
$maxSize = 2 * 1024 * 1024;
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "File upload failed.";
} elseif ($file["size"] > $maxSize) {
echo "File size must not exceed 2 MB.";
} else {
echo "File size is valid.";
}
}
?>
Sample Output
For a 1 MB file:
File size is valid.
For a 3 MB file:
File size must not exceed 2 MB.
Explanation
$_FILES["myfile"]["size"]returns the uploaded file size in bytes.1024 * 1024represents 1 MB in bytes.$maxSizestores the maximum permitted file size.- The condition rejects files larger than 2 MB.
Remember: PHP also has server configuration limits such as upload_max_filesize and post_max_size. Your application cannot accept a file larger than the server allows.
Concepts Covered
- File size validation
$_FILES["size"]- Bytes and megabytes
- Maximum upload size
Question 4: Validate File Extension Before Uploading
Problem Statement
Create a PHP program that allows only JPG, JPEG, and PNG files. Reject files with other extensions.
PHP Solution
<?php
if (isset($_FILES["image"])) {
$file = $_FILES["image"];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "File upload failed.";
} else {
$fileName = $file["name"];
$extension = strtolower(
pathinfo($fileName, PATHINFO_EXTENSION)
);
$allowedExtensions = [
"jpg",
"jpeg",
"png"
];
if (in_array($extension, $allowedExtensions, true)) {
echo "File extension is allowed.";
} else {
echo "Only JPG, JPEG, and PNG files are allowed.";
}
}
}
?>
Sample Output
Uploaded filename:
student.jpg
Output:
File extension is allowed.
Uploaded filename:
document.pdf
Output:
Only JPG, JPEG, and PNG files are allowed.
Explanation
pathinfo()extracts information from a filename.PATHINFO_EXTENSIONreturns its extension.strtolower()converts the extension to lowercase.in_array()checks whether the extension exists in the allowed list.
Important: File extensions can be changed or faked. Extension checking alone does not prove that a file is actually an image. Real applications should also check the file’s MIME type and content.
Concepts Covered
- File extension validation
pathinfo()PATHINFO_EXTENSIONstrtolower()in_array()
Question 5: Validate File MIME Type Using PHP
Problem Statement
Create a PHP program that checks whether an uploaded file is actually a JPEG or PNG image using its MIME type.
PHP Solution
<?php
if (isset($_FILES["image"])) {
$file = $_FILES["image"];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "File upload failed.";
} else {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file(
$finfo,
$file["tmp_name"]
);
finfo_close($finfo);
$allowedTypes = [
"image/jpeg",
"image/png"
];
if (in_array($mimeType, $allowedTypes, true)) {
echo "Valid image file.";
} else {
echo "Only JPEG and PNG images are allowed.";
}
}
}
?>
Sample Output
For a valid PNG image:
Valid image file.
For a PDF document:
Only JPEG and PNG images are allowed.
Explanation
finfo_open()creates a file information object.FILEINFO_MIME_TYPEtells PHP to identify the file’s MIME type.finfo_file()checks the uploaded temporary file.in_array()compares the detected MIME type against the allowed types.finfo_close()closes the file information resource.
MIME type checking is more reliable than checking only the filename extension, although no single check guarantees that a file is completely safe.
Concepts Covered
- MIME type validation
finfo_open()finfo_file()FILEINFO_MIME_TYPE- Allowed file types
Question 6: Validate an Image Using getimagesize()
Problem Statement
Create a PHP program that checks whether an uploaded file is a valid image and displays its width and height.
PHP Solution
<?php
if (isset($_FILES["image"])) {
$file = $_FILES["image"];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "Image upload failed.";
} else {
$imageInfo = getimagesize($file["tmp_name"]);
if ($imageInfo !== false) {
echo "Valid Image File<br>";
echo "Width: " . $imageInfo[0] . " pixels<br>";
echo "Height: " . $imageInfo[1] . " pixels";
} else {
echo "Uploaded file is not a valid image.";
}
}
}
?>
Sample Output
Valid Image File
Width: 1200 pixels
Height: 800 pixels
Explanation
getimagesize()checks image information from the uploaded file.$imageInfo[0]contains the image width.$imageInfo[1]contains the image height.- If the function returns
false, PHP could not recognize the file as an image.
Concepts Covered
- Image validation
getimagesize()- Image width and height
- Image information
Question 7: Upload a File with a Unique Filename
Problem Statement
Create a PHP program that uploads a file and saves it using a randomly generated filename instead of the original filename.
PHP Solution
<?php
if (isset($_FILES["myfile"])) {
$file = $_FILES["myfile"];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "Upload failed.";
} else {
$uploadDir = "uploads/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$extension = strtolower(
pathinfo($file["name"], PATHINFO_EXTENSION)
);
$allowedExtensions = ["jpg", "jpeg", "png", "pdf"];
if (!in_array($extension, $allowedExtensions, true)) {
echo "File extension is not allowed.";
} else {
$newFileName = bin2hex(random_bytes(16))
. "." . $extension;
$destination = $uploadDir . $newFileName;
if (move_uploaded_file(
$file["tmp_name"],
$destination
)) {
echo "File uploaded successfully.<br>";
echo "New Filename: " . htmlspecialchars(
$newFileName,
ENT_QUOTES,
"UTF-8"
);
} else {
echo "Unable to save the file.";
}
}
}
}
?>
Sample Output
File uploaded successfully.
New Filename: 8f31a7c2d5e9b4f6a1c8d3e7f0b2a5c9.jpg
<text color=”secondary” size=”xs”>The generated filename will be different each time.</text>
Explanation
random_bytes()generates random bytes.bin2hex()converts those bytes into hexadecimal characters.pathinfo()extracts the original extension.- The new filename avoids directly trusting the user’s original filename.
move_uploaded_file()saves the uploaded file.
Important: This example checks the extension only. A real upload system must also validate the file’s MIME type and size before saving it.
Concepts Covered
- Unique filenames
random_bytes()bin2hex()- File extension handling
- Safe file naming
Question 8: Upload Only PDF Documents
Problem Statement
Create a PHP program that accepts only PDF documents and rejects other file types. The uploaded file should be saved inside the uploads folder.
PHP Solution
<?php
if (isset($_FILES["document"])) {
$file = $_FILES["document"];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "Please select a valid PDF file.";
} else {
$extension = strtolower(
pathinfo($file["name"], PATHINFO_EXTENSION)
);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file(
$finfo,
$file["tmp_name"]
);
finfo_close($finfo);
if (
$extension !== "pdf" ||
$mimeType !== "application/pdf"
) {
echo "Only PDF documents are allowed.";
} else {
$uploadDir = "uploads/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$newFileName = bin2hex(random_bytes(16)) . ".pdf";
if (move_uploaded_file(
$file["tmp_name"],
$uploadDir . $newFileName
)) {
echo "PDF uploaded successfully.";
} else {
echo "Unable to save the PDF.";
}
}
}
}
?>
Sample Output
For a PDF file:
PDF uploaded successfully.
For a JPG file:
Only PDF documents are allowed.
Explanation
pathinfo()checks the file extension.finfo_file()detects the file’s MIME type.- Both checks must pass for the upload to continue.
random_bytes()creates a unique filename.move_uploaded_file()saves the PDF in the upload directory.
Concepts Covered
- PDF file validation
- MIME type checking
- Extension validation
- Unique filename generation
- File storage
Question 9: Upload Multiple Files Using PHP
Problem Statement
Create a PHP program that accepts multiple files and uploads them into the uploads folder. Allow only JPG, PNG, and PDF files up to 2 MB each.
PHP Solution
<?php
if (isset($_FILES["files"])) {
$uploadDir = "uploads/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$maxSize = 2 * 1024 * 1024;
$allowedTypes = [
"image/jpeg" => "jpg",
"image/png" => "png",
"application/pdf" => "pdf"
];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
foreach ($_FILES["files"]["name"] as $i => $originalName) {
$error = $_FILES["files"]["error"][$i];
$tmpName = $_FILES["files"]["tmp_name"][$i];
$fileSize = $_FILES["files"]["size"][$i];
if ($error !== UPLOAD_ERR_OK) {
echo "Upload failed for file " . ($i + 1) . ".<br>";
continue;
}
if ($fileSize > $maxSize) {
echo "File " . ($i + 1) . " exceeds 2 MB.<br>";
continue;
}
$mimeType = finfo_file($finfo, $tmpName);
if (!isset($allowedTypes[$mimeType])) {
echo "File " . ($i + 1) . " has an invalid type.<br>";
continue;
}
$extension = strtolower(
pathinfo($originalName, PATHINFO_EXTENSION)
);
if ($extension !== $allowedTypes[$mimeType]) {
echo "File " . ($i + 1) . " has a mismatched extension.<br>";
continue;
}
$newFileName = bin2hex(random_bytes(16))
. "." . $extension;
if (move_uploaded_file(
$tmpName,
$uploadDir . $newFileName
)) {
echo "File " . ($i + 1) . " uploaded successfully.<br>";
} else {
echo "Unable to save file " . ($i + 1) . ".<br>";
}
}
finfo_close($finfo);
}
?>
Required HTML form:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<button type="submit">Upload Files</button>
</form>
Sample Output
File 1 uploaded successfully.
File 2 uploaded successfully.
File 3 has an invalid type.
Explanation
multipleallows the user to select more than one file.files[]sends the selected files as an array.foreach()processes each uploaded file separately.- Each file is checked for upload errors and maximum size.
finfo_file()checks the MIME type.- The extension is checked against the detected MIME type.
- Each accepted file gets a unique filename.
Concepts Covered
- Multiple file uploads
$_FILESarraysmultipleattribute- File size validation
- MIME type validation
- File upload loops
Question 10: Build a Complete Secure Image Upload System
Problem Statement
Create a PHP program that allows a student to upload a profile image. The program must:
- Accept only JPG, JPEG, and PNG images.
- Allow a maximum file size of 2 MB.
- Validate the file extension and MIME type.
- Check whether the uploaded file is a valid image.
- Generate a unique filename.
- Save the image inside the
uploadsfolder.
PHP Solution
upload.php
<!DOCTYPE html>
<html>
<body>
<h2>Student Profile Image Upload</h2>
<form method="POST" enctype="multipart/form-data">
Select Profile Image:
<input type="file" name="profile" accept=".jpg,.jpeg,.png">
<br><br>
<button type="submit" name="upload">Upload Image</button>
</form>
<?php
if (isset($_POST["upload"])) {
if (!isset($_FILES["profile"])) {
echo "Please select an image.";
} else {
$file = $_FILES["profile"];
$maxSize = 2 * 1024 * 1024;
$allowedTypes = [
"image/jpeg" => ["jpg", "jpeg"],
"image/png" => ["png"]
];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "File upload failed.";
} elseif ($file["size"] > $maxSize) {
echo "Image size must not exceed 2 MB.";
} else {
$extension = strtolower(
pathinfo($file["name"], PATHINFO_EXTENSION)
);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file(
$finfo,
$file["tmp_name"]
);
finfo_close($finfo);
if (
!isset($allowedTypes[$mimeType]) ||
!in_array(
$extension,
$allowedTypes[$mimeType],
true
)
) {
echo "Only valid JPG and PNG images are allowed.";
} else {
$imageInfo = getimagesize($file["tmp_name"]);
if ($imageInfo === false) {
echo "Uploaded file is not a valid image.";
} else {
$uploadDir = "uploads/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$newFileName = bin2hex(random_bytes(16))
. "." . $extension;
$destination = $uploadDir . $newFileName;
if (move_uploaded_file(
$file["tmp_name"],
$destination
)) {
echo "<h3>Image Uploaded Successfully!</h3>";
echo "File Name: " .
htmlspecialchars(
$newFileName,
ENT_QUOTES,
"UTF-8"
);
} else {
echo "Unable to save the image.";
}
}
}
}
}
}
?>
</body>
</html>
Sample Output
Image Uploaded Successfully!
File Name: 8f31a7c2d5e9b4f6a1c8d3e7f0b2a5c9.jpg
<text color=”secondary” size=”xs”>The filename shown is an example. PHP generates a new random filename for each upload.</text>
Explanation
- The form uses
multipart/form-datato send the image. - PHP checks the upload error before processing the file.
- The size condition rejects images larger than 2 MB.
pathinfo()extracts the file extension.finfo_file()detects the MIME type.- The allowed extension must match the detected MIME type.
getimagesize()checks whether PHP can recognize the uploaded file as an image.random_bytes()generates a unique filename.move_uploaded_file()saves the validated image.
Concepts Covered
- Complete file upload system
- Image validation
- File size checking
- MIME type and extension validation
- Unique filenames
- Secure file handling
Key Takeaways
- PHP uses the
$_FILESsuperglobal to receive uploaded files. multipart/form-datais required for HTML file uploads.move_uploaded_file()saves an uploaded file.$_FILES["file"]["size"]provides the file size in bytes.$_FILES["file"]["error"]provides the upload status.pathinfo()extracts a file extension.finfo_file()helps identify the actual MIME type.getimagesize()checks image information.- Use an allowlist of permitted extensions and MIME types.
- Generate unique filenames instead of trusting original filenames.
- Never trust a filename or extension supplied by a user.
Frequently Asked Questions (FAQs)
1. What is file uploading in PHP?
File uploading in PHP allows users to send files from their devices to a web server through an HTML form.
2. What is the $_FILES superglobal in PHP?
$_FILES is a PHP superglobal that stores information about uploaded files, including filename, temporary location, size, MIME type, and upload error.
3. Why do we use multipart/form-data?
It tells the browser to encode form data in a format that supports file uploads. Without it, normal HTML forms cannot upload files correctly.
4. What is move_uploaded_file()?
move_uploaded_file() moves a file uploaded through PHP from its temporary location to a specified destination.
5. How can we check the uploaded file size in PHP?
Use $_FILES["file"]["size"]. The value is returned in bytes.
6. How do we restrict file uploads to JPG and PNG?
Check the file extension and MIME type against an allowlist. For additional image validation, use getimagesize().
7. What is the difference between a file extension and a MIME type?
A file extension is the ending of a filename, such as .jpg or .pdf. A MIME type describes the type of file, such as image/jpeg or application/pdf.
8. What is the purpose of $_FILES["file"]["tmp_name"]?
It contains the temporary server location where PHP stores the uploaded file before it is moved to its final destination.
9. How can we upload multiple files in PHP?
Use the multiple attribute in the HTML file input and give it an array-style name such as files[]. PHP can then process each file using a loop.
10. How can we make file uploads safer in PHP?
Validate file size, extension, MIME type, and file content. Generate random filenames, restrict the upload directory, and prevent uploaded files from being executed as server-side scripts. Store files outside the public web directory when possible.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
