In this project, we will learn how to upload files using PHP, validate them, and store them safely on the server.
File upload is used in:
- Profile pictures
- Documents upload
- Images in blogs
- Resume upload systems
What You Will Learn in This Project
- How file upload works in PHP
- Use of
$_FILESarray - Upload files to server folder
- Validate file type and size
- Secure file upload techniques
Project Features
- Upload image/file using HTML form
- Store file in
uploadsfolder - Prevent invalid file uploads
- Display uploaded file
Project Structure
project3/
│── uploads/
│── upload.php
│── view.php
How This Project Will Be Built (Flow)
- Create upload form
- Handle file using PHP
- Validate file
- Move file to uploads folder
- Display uploaded file
Form → PHP → Server Folder → Browser
Step 1: Create Upload Folder
Create a folder named uploads in your project directory.
⚠️ Make sure it has write permission.
Step 2: Create Upload Form
Create a file upload.php
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h2>Upload File</h2>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<br><br>
<input type="submit" name="upload" value="Upload File">
</form>
</body>
</html>
Step 3: Handle File Upload Using PHP
Add this PHP code above the HTML in upload.php
<?php
if (isset($_POST['upload'])) {
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$uploadDir = "uploads/";
if (move_uploaded_file($fileTmp, $uploadDir . $fileName)) {
echo "<p style='color:green;'>File uploaded successfully!</p>";
} else {
echo "<p style='color:red;'>File upload failed.</p>";
}
}
?>
Step 4: Test File Upload
- Open browser
- Go to:
http://localhost/upload.php - Select a file
- Click Upload
- Check
uploadsfolder
🎉 File should be uploaded.
Important Notes (Beginner Friendly)
enctype="multipart/form-data"is required$_FILESstores uploaded file detailsmove_uploaded_file()moves file securely
Security Issue (Important ⚠️)
This version allows any file upload.
We will fix this in next parts:
- File type validation
- File size limit
- Rename files
- Prevent PHP execution
Mini Task for Students
Try to:
- Upload only images
- Display uploaded image
- Rename file using timestamp
