how to create directory of date and month durning file upload into php

Click here for Govt Schemes

how to create directory of date and month durning file upload into php

To create a directory with the date and month during file upload in PHP, you can follow these steps:

  1. Set up the HTML form to handle file uploads:

html

 

<form action="upload.php" enctype="multipart/form-data" method="post">
<code>Select file to upload: <input name="fileToUpload" type="file" />
<input name="submit" type="submit" value="Upload File" /></code></form>

 

  1. Create the PHP script (upload.php) that will handle the file upload and directory creation:

php

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["fileToUpload"])) {
$targetDir = "uploads/"; // The base directory where files will be uploaded
$uploadDate = date("Y-m-d"); // Get the current date in the format 'YYYY-MM-DD'
$uploadMonth = date("F"); // Get the current month's name (e.g., January, February, etc.)

// Create a directory with the format 'YYYY/MM' (e.g., '2023/July')
$uploadDir = $targetDir . $uploadDate . "/" . $uploadMonth . "/";

// Check if the directory exists; if not, create it recursively
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$targetFile = $uploadDir . basename($_FILES["fileToUpload"]["name"]);

// Check if the file was uploaded successfully
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
}
else { echo "Sorry, there was an error uploading your file."; }
}
?>

In this example, the uploaded files will be stored in the "uploads" directory within subdirectories organized by date and month. For example, if you upload a file on July 25, 2023, it will be stored in "uploads/2023/July/".

Please ensure that the "uploads" directory has appropriate permissions (write access) to allow PHP to create subdirectories and store files. You can adjust the directory structure or naming convention based on your requirements. Additionally, it's essential to validate and sanitize user input when handling file uploads to enhance security.



Share on Pinterest
Share on LinkedIn
Share on WhatsApp
Share on Telegram



Latest POst

Recent Updates


Haryana Goverment Schemes