Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Call to undefined function random_bytes() [duplicate]

Tags:

php

I'm using php 5.6.23-0+deb8u1 and in my code I want use the function random_bytes but I get this error:

Fatal error: Call to undefined function random_bytes()

I want to know if I need to import something or isn't included in this version of php, in this case, how can I replace it?

like image 983
AgainMe Avatar asked Dec 08 '16 11:12

AgainMe


2 Answers

random_bytes() was introduced with PHP 7.

As stated in the manual:

Note: Although this function was added to PHP in PHP 7.0, a » userland implementation is available for PHP 5.2 to 5.6, inclusive.

You can use that userland implementation as a backport: https://github.com/paragonie/random_compat

like image 76
Narf Avatar answered Oct 03 '22 16:10

Narf


random_bytes was introduced with PHP7 (reference).

Alternatively for PHP versions below 7.0 like 5.6, 5.5 etc, you can use custom function to generate random number using function below.

if( !function_exists('random_bytes') )
{
    function random_bytes($length = 6)
    {
        $characters = '0123456789';
        $characters_length = strlen($characters);
        $output = '';
        for ($i = 0; $i < $length; $i++)
            $output .= $characters[rand(0, $characters_length - 1)];

        return $output;
    }
}
like image 23
Hassaan Avatar answered Oct 03 '22 16:10

Hassaan