Reputation: 143
I have a file input known as 'name=fileImage'. Now I have php code below where it checks to see if file exists in the folder (ImageFiles) or not:
if (file_exists("ImageFiles/" . $_FILES["fileImage"]["name"]))
{
}
My question is that if a file does exist in the folder, how can it be coded so that it still uploads the file but it gives it a different file name. Maybe something like automatically add a number at the end of the filename to give it a different file name?
Upvotes: 1
Views: 1486
Reputation: 1976
If you want to rename the uploaded file to a name of your own choice, you can try
<?php
//Any file name user/uploader has chosen/used on his/her computer
$tmp_name = $_FILES["domainfile"]["tmp_name"];
//Name you want
$name = "MyDesiredName.png"; //save as MyDesiredName.png
//Move/save file
move_uploaded_file($tmp_name, $name);
?>
Obviously this code will replace the old file everytime a new file gets uploaded.
To not to let this happen, you need to introduce some variable in the $name
and do $name++ and to find a way to store its value for future reference.
Upvotes: 0
Reputation: 324630
$_FILES
is just a variable, that happens to be superglobal and pre-populated with file upload data. Meaning you can easily change it.
For example:
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
}
// now use $_FILES['fileImage']['name'] just like you would normally
Upvotes: 5