Here's a complete tutorial in English to create a PHP application that uploads image or PDF files and automatically organizes them into folders based on the year, month, and date.
Requirements
PHP 7.4 or higher installed.
A web server like Apache or Nginx.
Basic knowledge of PHP and HTML.
Step-by-Step Tutorial
1. Setting Up the Project
Create a folder for your project, e.g., file_upload_project, and ensure it is accessible through your web server. Inside the folder, create the following files and directories:
index.php (for the upload form and processing logic)
uploads/ (this is where uploaded files will be stored; ensure it is writable)
2. Create the HTML Upload Form
<!-- index.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>Upload Image or PDF</h1>
<form action="index.php" method="post" enctype="multipart/form-data">
<label for="file">Choose a file (Image or PDF):</label>
<input type="file" name="file" id="file" required>
<button type="submit" name="submit">Upload</button>
</form>
</body>
</html>
3. Handle File Uploads
Add PHP logic to handle the file upload, validate the file type, and create the date-based folder structure.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
// Configuration
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf']; // Allowed MIME types
$uploadDir = 'uploads'; // Base upload directory
// Retrieve file details
$file = $_FILES['file'];
$fileName = basename($file['name']);
$fileTmp = $file['tmp_name'];
$fileType = mime_content_type($fileTmp);
$fileSize = $file['size'];
// Validate file type
if (!in_array($fileType, $allowedTypes)) {
die("Error: Invalid file type. Only images or PDFs are allowed.");
}
// Validate file size (optional)
if ($fileSize > 5 * 1024 * 1024) { // 5 MB limit
die("Error: File size exceeds 5MB.");
}
// Create date-based folders
$datePath = date('Y/m/d'); // e.g., 2025/01/27
$targetDir = "$uploadDir/$datePath";
// Create directories if they don't exist
if (!is_dir($targetDir)) {
mkdir($targetDir, 0777, true); // Create with full permission
}
// Define target file path
$targetFile = "$targetDir/$fileName";
// Move the uploaded file to the target directory
if (move_uploaded_file($fileTmp, $targetFile)) {
echo "File uploaded successfully! <br>";
echo "File path: $targetFile";
} else {
echo "Error: Failed to upload file.";
}
}
?>
4. Directory Structure After Upload
After an upload on, say, January 27, 2025, the directory structure will look like this:
file_upload_project/
├── index.php
├── uploads/
│ └── 2025/
│ └── 01/
│ └── 27/
│ └── uploaded_file_name.pdf
Key Points in the Code
Allowed MIME Types: Ensure only specific file types are allowed by validating the MIME type using mime_content_type().
Folder Creation:
The date('Y/m/d') function generates the folder path based on the current date.
The mkdir() function creates the directory structure recursively if it doesn't already exist.
File Validation:
Check the file type to prevent uploads of unauthorized file formats.
Optionally, restrict file sizes using $fileSize.
File Path:
Files are saved in the uploads/YYYY/MM/DD/ structure.
5. Enhancements and Security Measures
Sanitize File Names: Prevent issues with special characters in file names.
$fileName = preg_replace("/[^a-zA-Z0-9\.\-\_]/", "", $fileName);
Unique File Names: Avoid overwriting files by appending a unique ID or timestamp.
$fileName = uniqid() . "_" . $fileName;
Restrict File Execution: Prevent uploaded files from being executed as scripts by adding an .htaccess file in the uploads/ directory:
# .htaccess
<FilesMatch "\.(php|pl|py|jsp|asp|aspx|sh|cgi)$">
Order Deny,Allow
Deny from all
</FilesMatch>
Error Handling: Use more robust error handling to provide user-friendly feedback during upload failures.
6. Testing the Application
Start your web server and navigate to the index.php file in your browser.
Select an image or PDF and click "Upload."
Check the uploads/ directory to ensure the file is correctly saved in the date-based folder structure.
Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.
Post a Comment for "PHP File Upload Tutorial Automatically Organize Images and PDFs by Folder Date"