سؤال

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! ';
}
هل كانت مفيدة؟

المحلول

You can do:

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

نصائح أخرى

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top