0

How do you generate random names for files in php7? random_bytes us returning symbols like _шИ ¶.png What other function can I use?

Edit: I guess I could use uniqueid() but isn't it a bit old?

pidari
  • 419
  • 2
  • 4
  • 13
  • 3
    Nothing wrong with using uniqid(). It's not deprecated or anything. You might as well say that `echo` is too old. – Cave Johnson Dec 02 '17 at 01:42
  • 2
    Although, wrt uniqid - "This function does not create random nor unpredictable string. This function must not be used for security purposes." - https://stackoverflow.com/questions/4070110/how-unique-is-uniqid So *the requirements for "random"* should be used to select a solution .. – user2864740 Dec 02 '17 at 01:57

1 Answers1

1

You can modify random_bytes's output to limit it to the printable character range.

Example:

// Ascii 126=~, 32=[space], so the lower ASCII printable block
define('RANDOMIZVI_RANGE_DEFAULT', 126-32);

function randomizvi(int $length, $range = RANDOMIZVI_RANGE_DEFAULT){
    $bytes = random_bytes($length);
    for($i = 0;$i < $length;$i++){
        $bytes[$i] = chr((ord($bytes[$i]) % $range) + 32);
    }
    return $bytes;
}

It's kind of a crude solution, but it works. Note that this particular implementation will be biased slightly towards certain characters.

If you don't really need random filenames, it might be simpler to just number them, which avoids possibilities of collisions.

Lux
  • 1,540
  • 1
  • 22
  • 28