Rename files with random names using php

Asked

Viewed 597 times

0

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

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

However, the file that had the name "exemplo1.gif" is now called "d8030d37e9exemplo1.gif", the next file "d8030d37e9exemplo2.gif"...

So the adjustments I’m having trouble making are:

  1. The new file name should not contain the original name
  2. The start of the new name is repeated for all renamed files ("d8030d37e9")

2 answers

3


Basically this:

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

  • we add a rand() not to depend solely on time() (which can easily repeat in loop);

  • we take the original name of rename.

  • 1

    It worked exactly as I wanted, thank you!

1

In the version of PHP 7 there is the random_byte that theoretically is safer 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 so cryptographically secure pseudo-random. The bin2hex is used to return in hexadecimal formed, which is the common.

At the end it will have a random 24 digit extension name to each file of the foreach.

  • Thank you, also worked as desired.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.