user3332711
user3332711

Reputation: 31

Add date/time to uploaded filenames in php

Is there anyway to add date/time or any other filename-edits that will prevent overwriting in this php code:

$name = $_FILES['file']['name'];

or this code:

if (move_uploaded_file($tmp_name, $location.$name)) {
    echo 'file uploaded! ';
}

Upvotes: 0

Views: 6069

Answers (3)

DusteD
DusteD

Reputation: 1410

I hope that the family of the patient have been notified!

$path=$_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$base = pathinfo($path, PATHINFO_FILENAME);
$name = $base.date("Y-m-d_H_i_s.").$ext;

You what you want is to prevent same filename for different files, you can use a hash of the data inside the file instead:

$path=$_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$base = pathinfo($path, PATHINFO_FILENAME);
$md5 = md5_file($path);
$name = $base.'_'.$md5.'.'.$ext;

You can also combine these:

$path=$_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$base = pathinfo($path, PATHINFO_FILENAME);
$md5 = md5_file($path);
$name = $base.'_'date("_Y-m-d_H_i_s.").$md5.$ext;

More info here:

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

http://php.net/manual/en/function.md5-file.php

http://php.net/pathinfo

Upvotes: 1

Oladapo Omonayajo
Oladapo Omonayajo

Reputation: 980

You can do:

<?php
    if (move_uploaded_file($tmp_name, $location.time().'_'.$name)) {
        echo 'file uploaded! ';
    }
?>

Upvotes: 1

flth
flth

Reputation: 51

Do you like to keep the original filename and add e.g. the date at the end? You'll need to split the filename into name and extension, then add the date to the end of name and glue it all together again

Upvotes: 0

Related Questions