John Davidson

wordpress - How to add a random name so that files won't replace php

0 comments
Message:


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.



My Answer:
You can generate a random name for the uploaded file by appending a timestamp to the file name. Here's how you can modify your code to achieve this:

Replace the line where you define the $file_name variable with the following code:

php
$file_name = time() . '_' . $_FILES['attachment']['name'];


This will append the current timestamp to the original file name, ensuring that each uploaded file has a unique name.

Additionally, you can also add a random number to the file name for extra uniqueness. Here's how you can modify the code further:

php
$file_name = time() . '_' . rand(1000, 9999) . '_' . $_FILES['attachment']['name'];


This will append a random 4-digit number to the file name along with the timestamp.

By making these changes, each uploaded file will have a unique name and won't replace existing files with the same name.

Rate this post

4 of 5 based on 2216 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us