Search code examples
phpfileuploadrenaming

Trying to rename a file when uploading and it wont work


Hey i am trying to change a file name on upload if it exist but seems i have a problem. here is the code..

$tempfilename = $filename["name"]; 
while(file_exists($location . $tempfilename))
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
    $shuffled = str_shuffle($chars);
    $stringa = substr($shuffled,0,7);
    move_uploaded_file($filename["tmp_name"], $location . $filename["name"]);
    $tempfilename = $stringA.$filename["name"];
}
move_uploaded_file($filename["tmp_name"], $location.$stringa.$filename["name"]);
clearstatcache();

This doesn't seem to work and

Don't know what I am missing.


Solution

  • PHP variable names are case sensitive.

    $stringA !== $stringa
    

    However, rather than all the messing about with shuffling strings etc, have you considered just using a counter?

    $tempfilename = $filename["name"];
    for ($i = 0; file_exists($location . $tempfilename); $i++) {
        $tempfilename = $i . $filename["name"];
    }
    move_uploaded_file($filename["tmp_name"], $location . $tempfilename);