0

I want to add validation or change the file name if there is a file name that already exists in the folder

$image = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$target_dir = "../file/upload/201902/28/";

move_uploaded_file($tmp, $target_dir.$image);
  • 1
    Add validation or change the file name? It’s not the same thing – Moses Schwartz Apr 10 '19 at 01:49
  • I'd suggest _you_ doing the naming using a unique id/filename (uniqid should do) to avoid the hassle and worry of collision/clobbering. However: https://stackoverflow.com/questions/4070110/how-unique-is-uniqid – Progrock Apr 10 '19 at 02:11
  • You can do something like add an incrementing postfix/prefix if the file exists. But I personally wouldn't trust a user generated file name. An alternative to the above is to use something like a hash of the file, and if you want to handle duplicate files, add an incrementer. – Progrock Apr 10 '19 at 02:27
  • 2
    Suffice to say, to check if a file already exists, you can use Php's `file_exists` function. – Progrock Apr 10 '19 at 02:32

1 Answers1

0

First of all validation and changing file name is not same... You can find file name if exist in that particular folder by "file_exists" php function.

To avoid this problem, you need to take unique filename by various method... You can take timestamp as filename....

$image = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$time=time();
$filename = $tmp."_".$time;
$target_dir = "../file/upload/201902/28/";
move_uploaded_file($filename, $target_dir.$image);
  • A couple of problems, tmp_name will be a full path. Adding time, may not be enough for uniqueness, you want at least micro-time. You make no file system checks for files that already exist. Your move line, takes likely a non-existing path/file, and tries to use the untrusted name provided by the browser, for the destination. – Progrock Apr 10 '19 at 09:26
  • This is the simple case.. If you want more secure check this https://stackoverflow.com/a/18705701/9047299 – Md. Mohaiminul Hasan Apr 10 '19 at 09:41