CancelImage Upload

How to rename an uploaded file to give it a unique name with PHP

If you own an interactive website where your users can upload their files, you will need to insure that each file has a unique name that can be used as an identifier. One way to accomplish this task is to add a timestamp to the filename. Granted two users could upload a file with exactly the same name at exactly the same time. But unless you have a website with billions of visitors per day you should be safe.

As you could probably guess the function to change a file's name goes under the name of rename(). The other function that we will use in the following example is file_exists(), simply to check if the file and path specified are indeed correct.

<?php

$tmp_name = "file.txt";

$new_name = "file".time().".txt";

if(file_exists($tmp_name))
{

       if(rename($tmp_name, $new_name))
       {

              echo "<i>".$tmp_name."</i> has been renamed to: <i>".$new_name."</i>";

       }
}
else
{

       echo "The file <i>".$tmp_name."</i> could not be found.";

}

?>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com