简体   繁体   中英

How do I rename a filename to a random filename in PHP?

I have a .php file with a random name. And I want to rename it to something another random name when a specific button was hit.

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;

}

if (isset($_SESSION['submit'])) {
    rename(, generateRandomString())
}

I have this code here and I think that I did everything right, but I don't know how to do the rename function

There is a rename function that does exactly what you want. Also you can use uniqid for generating unique names for your files.

you need to look up the rename() function in the PHP docs: http://php.net/manual/en/function.rename.php

if (isset($_SESSION['submit'])) {

    $oldFileName = 'foo.txt';
    $newFileName = generateRandomString() . '.txt';

    rename($oldFileName, $newFileName);

}

This is it in its basic form, but in production you would want to handle errors and store the new filename etc.

To improve the function .

This shuffles an array with the letters/numbers and take the ten first characters.

This should be more efficient than looping.

$characters = array ('0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
);
shuffle($characters);
return implode("", array_slice($characters, 0,10));

https://3v4l.org/7dUiN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM