I have little upload script and i wonder how to rename a file if the file with same name already exists.

Edited by web3: n/a

8 Years
Discussion Span
Last Post by hemgoyal_1990

Why not just append the file name with a time stamp like:



Edited by Ezzaral: Added [code] [/code] tags. Please use them to format any code that you post.


Good idea.
Most filenames for uploaded files are pretty meaningless once automatically renamed, but this isn't a problem. Some use a DB to link a 'pretty' false name to a datestamped (renamed!) name. A dynamically-created link for the image could be:

<a href="images/user127_372183294748909.jpg" title="...">dogkennel.jpg</a>

Which could be produced from something like:

id (Primary Key)
systemurl (e.g. images/user127_372183294748909.jpg)
prettyname (e.g. dogkennel.jpg)

Using just date() will give you an integer (to the nearest second).

Edited by diafol: n/a


Another idea, before uploading you can check , if the file with same name exists using file_exists() function and if another file found you can rename it using rename().
This way it will be possible what you are trying to do, but this is not the best way to do it.
The best way is stated above, while you uploading the files to server, do that renaming stuff that time only.like whats explained above, appending the current timestamp to the file name and then moving it to server.


You May Use Below Specified Script:

$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    $ne_filename = rename($filename, "your_file_path/new_file_name.ext");
    //Your File Uploading Code Here.
} else {
    //Your File Uploading code.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.