PiTheNumber PiTheNumber - 9 months ago 51
PHP Question

Convert random values from /dev/urandom

As mentioned in the comments of

it is weak in security and we should use /dev/urandom instead. My problem is that from urandom I get a binary string.

How do I convert this binary string to 0-9a-zA-Z?

Looks like
does not work here.


Just for the record the full function:

function randomFromDev($len)
    $fp = @fopen('/dev/urandom','rb');
    $result = '';
    if ($fp !== FALSE) {
        $result .= @fread($fp, $len);
        trigger_error('Can not open /dev/urandom.');
    // convert from binary to string
    $result = base64_encode($result);
    // remove none url chars
    $result = strtr($result, '+/', '-_');
    // Remove = from the end
    $result = str_replace('=', ' ', $result);
    return $result;