Uploading images via a form is a common task in web development. Whether you’re building a contact form, profile system, or admin panel, it’s important to handle file uploads securely and efficiently. This tutorial covers everything from setting up the form to processing uploads in PHP, validating file types, and restricting file sizes.
To get your PHP tasks done more securely and professionally you may need to hire a PHP developer.
🧰 Prerequisites for Uploading Files with PHP
Before you begin, ensure the following:
- You have a working PHP server (localhost like XAMPP/WAMP or a live host).
- You’ve created a directory structure to store uploaded files.
Recommended Directory Structure:
/forms/
├── uploads/ ← Folder to store uploaded files
├── form.html ← The HTML form file
└── file_process.php ← PHP file to handle the form submission
📝 Creating an HTML Form to Upload Images
To upload files, your form must:
- Use the
POST
method (notGET
) - Include the
enctype="multipart/form-data"
attribute
Note:
Be sure your file upload form has attribute enctype=”multipart/form-data” otherwise the file upload will not work.Source php.net
Here’s the form:
<form enctype="multipart/form-data" action="file_process.php" method="post">
<input type="text" name="name" placeholder="Please enter your name…" />
<input type="email" name="email" required placeholder="Enter your email…" />
<label>Upload Your Image:
<input type="file" name="profile_image" />
</label>
<input type="submit" value="Submit Form" />
</form>
🔍 HTML Form Explained
enctype="multipart/form-data"
allows file transfermethod="POST"
ensures secure data handling- Each field uses the
name
attribute so PHP can access its value - The
file
input enables users to upload an image required
ensures the email field is not empty before submission
🧪 What Happens When You Submit the Form?
When the form is submitted:
- Data is sent via
POST
tofile_process.php
- PHP reads the input fields (
name
,email
) and uploaded file - The file is validated (type and size)
- If valid, the file is moved to the
uploads/
directory - A path to the uploaded image is stored in a PHP variable
🧠 Processing the Form in PHP (file_process.php
)
Here’s a simple script to handle the form:
<?php
extract($_POST);
$fileType = $_FILES["profile_image"]["type"];
$fileSize = $_FILES["profile_image"]["size"];
// File size check (max 2MB)
if ($fileSize / 1024 > 2048) {
echo "File size should be less than 2MB.";
exit();
}
// File type validation
$allowedTypes = [
"image/png",
"image/gif",
"image/jpg",
"image/jpeg",
"application/pdf",
"application/zip",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
];
if (!in_array($fileType, $allowedTypes)) {
echo "Unsupported file type. Allowed types: JPG, PNG, GIF, PDF, ZIP, DOCX.";
exit();
}
// Set upload path
$upFile = "uploads/" . date("Y_m_d_H_i_s") . $_FILES["profile_image"]["name"];
if (is_uploaded_file($_FILES["profile_image"]["tmp_name"])) {
if (!move_uploaded_file($_FILES["profile_image"]["tmp_name"], $upFile)) {
echo "Failed to move uploaded file.";
exit();
}
} else {
echo "Possible file upload attack.";
exit();
}
$profile_image = $upFile;
echo "File uploaded to: " . $profile_image;
?>
🧼 PHP Code Breakdown
📤 extract($_POST);
Automatically creates variables like $name
and $email
from form inputs.
📏 File Size Restriction
Limits file upload to 2MB:
if ($fileSize / 1024 > 2048) { ... }
🧾 File Type Validation
Ensures only supported file types (JPG, PNG, PDF, etc.) are accepted:
$allowedTypes = [...];
if (!in_array($fileType, $allowedTypes)) { ... }
📁 Move File to Directory
Moves uploaded file from temporary storage to the desired folder:
move_uploaded_file($_FILES["profile_image"]["tmp_name"], $upFile)
🧰 Reusable PHP Function to Upload Files
A cleaner approach is to use a reusable function:
define("ROOT_DIR", dirname(__FILE__));
function wc_upload_image_return_url($image_submit) {
if (empty($image_submit) || $image_submit['error'] != 0) {
return "Nothing uploaded.";
}
$fileType = $image_submit["type"];
$fileSize = $image_submit["size"];
if ($fileSize / 1024 > 2048) {
return "File size must be less than 2MB.";
}
$allowedTypes = [
"image/png", "image/gif", "image/jpg", "image/jpeg",
"application/pdf", "application/zip",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
];
if (!in_array($fileType, $allowedTypes)) {
return "Invalid file type.";
}
$filename = date("Y_m_d_H_i_s") . $image_submit["name"];
$uploadPath = ROOT_DIR . "/uploads/" . $filename;
if (is_uploaded_file($image_submit["tmp_name"])) {
if (!move_uploaded_file($image_submit["tmp_name"], $uploadPath)) {
return "Error moving file.";
}
return "uploads/" . $filename;
} else {
return "Possible file upload attack.";
}
}
✅ How to Use It:
if (isset($_FILES["profile_image"])) {
$uploaded_file_url = wc_upload_image_return_url($_FILES["profile_image"]);
echo "Uploaded File URL: " . $uploaded_file_url;
}
📌 Final Tips
- Always validate file type and size on the server
- Never trust user input blindly—use proper sanitization
- Avoid uploading executable files like
.exe
unless absolutely necessary - Use unique filenames (timestamp, user ID, etc.) to avoid overwriting
✅ Summary
Step | Description |
---|---|
Create HTML form | Use POST and multipart/form-data |
Process form in PHP | Use $_POST and $_FILES |
Validate file size & type | Use if statements and allowed types |
Move uploaded file | Use move_uploaded_file() |
Store image path | Save the image URL in a variable |