Adding timestamp and custom name to a File uploaded via PHP

20.4k views Asked by At

I was looking for a way to add a timestamp and a custom name to a file uploaded to my server via php. I does some readings on $_FILE[] to understand its arguments, but the official PHP docs give no detailed explanation.

This is the code I use to upload, where could I include the timestamp (date('m-d-Y_H:i:s')) and name (ie: "myFile") to create a uniq name for files that are uploaded?

Thanks!

$date = date('m-d-Y_H:i:s');    
$file_path = "uploads/{$_POST['name']}/";

    if (!file_exists("uploads/{$_POST['name']}")) {
        mkdir("uploads/{$_POST['name']}", 0777, true);  
    } else {
        echo 'folder already exists!';
    }

    $file_path = $file_path . basename($_FILES['zipFile']['name']);
    if (move_uploaded_file($_FILES['zipFile']['tmp_name'], $file_path)) {
        echo "success";
    } else {
        echo "fail";
    }
6

There are 6 answers

1
Dinuka Dayarathna On BEST ANSWER

Hope you can get an idea

$file_path = "uploads/".$_POST['name']."/";   
$newfile = $_POST['NAME'].date('m-d-Y_H:i:s')'.zip'; //Please use date('m-d-Y_H-i-s') for Linux. 
$filename = $file_path.$newfile;
if(!file_exists($filename))
{
    if(move_uploaded_file($_FILES['zipFile']['tmp_name'],$filename))
    {
        // Other codes
    }
}
else
{
    echo 'file already exists';
}
0
Devsome On

You can safe your uploaded file data to a Database and add all the datas you need like timestamp, ip from the uploader, file size, file name

0
phpfresher On

if i understood your question correctly.. is this what u r asking for..

       if(is_uploaded_file($tmp_name))
        {
            $org_name = date('m-d-Y_H:i:s')."_".$yourname;
            $dest = "uploads/$org_name";
            move_uploaded_file($tmp_name, $dest);
        }
0
René Höhle On

Its very simple add the filename behind your $file_path.

$filename = date('m-d-Y_H:i:s').'_'.md5(time).'.zip';

if (move_uploaded_file($_FILES['zipFile']['tmp_name'], $file_path.'/'.$filename)) {
    echo "success";
} else {
    echo "fail";
}

If you are sure that there are only zip files you can use the extension directly otherwise you should use the placeholder.

0
Bruce On

Use this to change custom name +(plus) time-stamp Add your custom name in

your_custom_name provide what name your what...

$filename=$_FILES[upload][name];
$ext=substr($filename,strrpos($filename,'.')+1);
$fname=date("Y-m-d-H-i-s")."-";
$fname.="your_custom_name"."-";
$fname.=uniqid().".".$ext;
$ext=strtolower($ext);
if(move_uploaded_file($_FILES[upload][tmp_name], "../images/products/".$fname)) {
   echo "success";
} else {
    $er_imgs="Failed";
}
0
RainHunter On

You cannot use ":" in your filename. replace it with "-":

$filename= 'yourprefix_' . date('d-m-Y_H-i-s') . '.zip';