user6579134
user6579134

Reputation: 839

rename file to current date before upload with php

i just moved from asp to php and i'm able to upload files to the server correclty. Now what i want to do is to rename the file before the upload is done and also echo the newly named file

<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size =$_FILES['image']['size'];
      $file_tmp =$_FILES['image']['tmp_name'];
      $file_type=$_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

      $expensions= array("jpeg","jpg","png");

      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152){
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true){
         move_uploaded_file($file_tmp,"../complains_photos/".$file_name);
         echo $file_type;
      }else{
         print_r($errors);
      }
   }
?>
<html>
   <body>

      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="image" />
         <input type="submit"/>
      </form>

   </body>
</html>

Upvotes: 0

Views: 1369

Answers (2)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Change move_uploaded_file(...); statement in the following way,

move_uploaded_file($file_tmp,"../complains_photos/".date("d-m-Y").".".$file_ext);

You can change the date format as per your preference.

Reference: http://php.net/manual/en/function.date.php

Upvotes: 0

Rob Ruchte
Rob Ruchte

Reputation: 3707

Just change the name that you are passing to the move_uploaded_file function. Something like this:

$destinationFileName = date('Ymd').'.'.$file_ext;
move_uploaded_file($file_tmp,"../complains_photos/".$destinationFileName);

Also change your echo to send $destinationFileName

Upvotes: 1

Related Questions