Renaming files with random names using php

0

I need to randomly rename all files with the .gif extension in a directory. I was able to, using the following code:

$nome = substr(hash('md5',time()),0,10);
foreach (glob("*.gif") as $arquivo) {
    rename($arquivo, $nome . basename($arquivo));
}

But the file that had the name "example1.gif" is called "d8030d37e9example1.gif", the next file "d8030d37e9example2.gif" ...

So the settings that I can not do are:

  • The new file name should not contain the original name
  • The start of the new name is repeated for all renamed files ("d8030d37e9")
  • asked by anonymous 25.01.2017 / 02:08

    2 answers

    3

    Basically this:

    foreach (glob("*.gif") as $arquivo) {
        $nome = substr(hash('md5',time().rand()),0,10);
        rename($arquivo, $nome.'.gif');
    }
    
    • We have passed the generation of the name to the loop, so that it is renewed;

    • We add rand() to not only depend on time() (which can loop easily);

    • We took the original name of rename .

    25.01.2017 / 02:11
    1

    In the PHP 7 version there is the random_byte that is theoretically more secure rather than relying on time.

    foreach (glob("*.gif") as $arquivo) {
    
         $nome = bin2hex( random_bytes(12) );    
         rename($arquivo, $nome . '.gif');
    
    }
    

    This will use the function random_byte will return generate 12 bytes in a way Cryptographically secure pseudo-random . The bin2hex is used to return in hexadecimal, which is the common .

    At the end you will have a random 24-digit extension name for each foreach .

        
    25.01.2017 / 08:21