In this part of Project 3 (File Upload System), we will learn how to display uploaded files safely without exposing the server to security risks.
What You Will Learn in This Part
- List uploaded files from a folder
- Display image previews
- Prevent direct execution of files
- Apply basic security best practices
Why Secure Display Is Important
Displaying uploaded files incorrectly can:
- Execute malicious scripts
- Expose server files
- Cause security vulnerabilities
We will display files only as content, not as executable scripts.
Step 1: Create a File Listing Page
Create a file named view.php
Step 2: Scan Upload Directory
Add this PHP code to view.php
<?php
$uploadDir = "uploads/";
$files = scandir($uploadDir);
?>
Step 3: Display Uploaded Files Safely
<!DOCTYPE html>
<html>
<head>
<title>Uploaded Files</title>
</head>
<body>
<h2>Uploaded Files</h2>
<?php
foreach ($files as $file) {
if ($file == '.' || $file == '..') {
continue;
}
$filePath = $uploadDir . $file;
$fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($fileExt, ['jpg', 'jpeg', 'png', 'gif'])) {
echo "<div style='margin-bottom:15px;'>";
echo "<img src='$filePath' width='200'><br>";
echo "</div>";
} else {
echo "<p><a href='$filePath' target='_blank'>$file</a></p>";
}
}
?>
</body>
</html>
Step 4: Test File Display
- Upload some images
- Open:
http://localhost/view.php - Images should display as previews
- Other files show as download links
Security Best Practices (Very Important)
1. Prevent PHP Execution in Uploads Folder
Create a .htaccess file inside uploads/
php_flag engine off
This prevents PHP files from executing.
2. Never Trust User File Names
We already:
- Renamed files
- Validated extensions
This avoids:
- File overwrite
- Script injection
Common Beginner Mistakes
- Directly echoing file names without validation
- Allowing
.phpuploads - No restriction on upload folder
Mini Task for Students
Try to:
- Add delete file option
- Show file size
- Sort files by upload time
Project 3 Completed 🎉
You have built:
- Secure file upload
- Validation
- Safe file display
This is real-world PHP knowledge.
