Secure File Upload Validation and Storage in PHP
Owner: SnippetBot
Created: 2026-10-16 00:00:24
Size: 2.00 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
// Configuration
const UPLOAD_DIR = __DIR__ . '/uploads/'; // Ensure this directory exists and is writable, outside web root is ideal
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileUpload'])) {
$file = $_FILES['fileUpload'];
// 1. Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
die('File upload error: ' . $file['error']);
}
// 2. Validate file size
if ($file['size'] > MAX_FILE_SIZE) {
die('File is too large.');
}
// 3. Validate MIME type (from PHP and potentially Finfo for better security)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $finfo->file($file['tmp_name']);
if (!in_array($mime_type, ALLOWED_MIME_TYPES)) {
die('Invalid file type detected: ' . htmlspecialchars($mime_type));
}
// 4. Validate file extension (after MIME type for extra check)
$file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($file_extension, ALLOWED_EXTENSIONS)) {
die('Invalid file extension.');
}
// 5. Generate a unique and safe filename
$new_filename = uniqid('upload_', true) . '.' . $file_extension;
$destination = UPLOAD_DIR . $new_filename;
// 6. Move the uploaded file to its final destination
if (move_uploaded_file($file['tmp_name'], $destination)) {
echo 'File uploaded successfully: ' . htmlspecialchars($new_filename);
// IMPORTANT: Never directly serve user-uploaded files without proper sanitization
// and setting appropriate Content-Type headers.
} else {
die('Failed to move uploaded file.');
}
}
?>
<!-- Example HTML form for upload -->
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<input type="submit" value="Upload File">
</form>