skip to Main Content
if(isset($_FILES['attachment'])){
      $errors= array();
      $file_name = $_FILES['attachment']['name'];
      $file_size =$_FILES['attachment']['size'];
      $file_tmp =$_FILES['attachment']['tmp_name'];
      $file_type=$_FILES['attachment']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['attachment']['name'])));
      
      $extensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 2097152){
         $errors[]='File size must be excately 2 MB';
      }
      
   }
    $sql = $wpdb->prepare( "INSERT INTO ".$tablename." (post_id, name, email, price, author, post_title, purchase_type, closing_date, concessions_amount, insp_from, insp_to, seller_charge, emd, home_warranty, seller_occupancy, attachment ) VALUES ( %d, %s, %s, %d, %s, %s, %s, %s, %d, %s, %s, %d, %d, %s, %s, %s )", $id, $name, $email, $price, $author, $post_title, $purchase_type, $closing_date, $concessions_amount, $insp_from, $insp_to, $seller_charge, $emd, $home_warranty, $seller_occupancy, $file_name );
    
    
    
    if(empty($errors)==true){
        
          function tp_wordpress_uploads_directory_path() {
    $upload_dir = wp_upload_dir();
    return $upload_dir['basedir'] . "/offers/";
}
        $upload_check =  move_uploaded_file($file_tmp,tp_wordpress_uploads_directory_path().$file_name);
         
      }

Right now system is replacing existing file, can anyone help to add a random number so that file’s names won’t match, may be by adding currrent time and date into?
I know how to rand(); works but not getting the way to implement it into my code.

2

Answers


  1. PHP has a built-in function specifically for generating random filenames:

    https://www.php.net/manual/en/function.tempnam.php

    If you really want to append a random number to the filename then you could use:

    $file_name = $_FILES['attachment']['name'].rand(1,10000);
    

    However, there’s no guarantee it won’t generate the same number twice or more times, resulting in the file being overwritten again.

    Login or Signup to reply.
  2. If the user is logged in then you can use user’s id or post’s id (in this case after inserting the post) and timestamp as a filename, assuming that user’s id or post’s id is unique.

    // or use post's id
    $filename = $_SESSION['user_id'].'-'.time();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search