To Set DateTime With FileName While Uploading in PHP here is only 3 steps to append a timestamp to the filename in PHP,
- Create a HTML form with input file type.
- Create PHP code to upload the file.
- Setting the date and time on the name of the file using PHP
date()
function.
Note:
Do not forget to add enctype="multipart/form-data"
on form tag, like below.
1 |
<form method="POST" enctype="multipart/form-data"> |
Also Read: Display Current Date and Time in HTML using JavaScript
Create HTML Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<html> <body> <form method="POST" enctype="multipart/form-data"> <table> <tr> <td>Image <input type="file" name="userImage"> </td> </tr> <tr> <td> <input type="submit" value="submit" name="sub"> </td> </tr> </table> </form> </body> </html> |
Also Read: How to Validate Date String in PHP
PHP Code to Append a Timestamp To The Filename
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php if(isset($_POST['sub'])){ if($_FILES['userImage']['name']){ // here is the current date time timestamp $time = date("d-m-Y")."-".time(); // here we set it to the image name $fileName = $_FILES['userImage']['name']; $fileName = $time."-".$fileName ; // upload that image into the directory name: images move_uploaded_file($_FILES['userImage']['tmp_name'], "images/".$fileName); $img="images/".$_FILES['userImage']['name']; }else{ echo "Something went wrong"; } } ?> |
Code Explanations:
- On the first line of code, we check the button clicked or not using PHP
isset()
. - Then we check the Image file is exists or not in PHP if condition.
- Get the current date and time in PHP using the PHP
date("d-m-Y")
function.$time = date("d-m-Y")."-".time();
- That time variable is appended to the file name using the concatenation operator.
$fileName = $_FILES['userImage']['name'];
$fileName = $time."-".$fileName ;
- At the last image will upload using PHP
move_uploaded_file($tempName, "path/".$fileName )
Here are the complete explanations of how we set or attach the timeWith File Name While Uploading in PHP.
Live View of Append a Timestamp To The Filename
To know more about handling file uploads in PHP, you can check the official documentation here, https://www.php.net/manual/en/features.file-upload.php
Also check:
- How to Get HTML Tag Value in PHP
- How to Keep Value After Page Reload in PHP
- 2 Ways to Open URL in New Tab Using JavaScript
- How to Embed PDF in Website Using HTML
Happy Coding..!
[…] Set DateTime With FileName While Uploading in PHP […]
Thanks it works