user2293381
user2293381

Reputation:

Generate random structured data with PHP

Im wondering how can I go on creating a random PHP value with similar structure as IPv6

Example: 2001:0db8:85a3:0042:1000:8a2e:0370:7334:nc21

I could use mt_rand(0000,9999).":"....... and so on But this creates only numerical values, and its redundant. Is there a simpler way of doing it altha-numerically in say a function?

Thanks every one for feedback and information, in the end I choose to go with the following code bit

$randomString = sha1(dechex(mt_rand(0, 2147483647)));
$token = implode(':', str_split($randomString, 4));

Result:

9ec0:4709:926e:4cbf:fa87:2ac3:03da:f547:485b:6464

Upvotes: 1

Views: 540

Answers (3)

Baba
Baba

Reputation: 95131

Avoid using rand see str_shuffle and randomness try :

echo myRand(36);

Output

023c:631e:f770:ec5b:f06b:917a:b839:4aea:45b7

Function Used

function myRand($length, $sep = ":", $space = 4) {
    if (function_exists("mcrypt_create_iv")) {
        $r = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
    } else if (function_exists("openssl_random_pseudo_bytes")) {
        $r = openssl_random_pseudo_bytes($length);
    } else if (is_readable('/dev/urandom')) {
        $r = file_get_contents('/dev/urandom', false, null, 0, $length);
    } else {
        $i = 0;
        $r = "";
        while($i ++ < $length) {
            $r .= chr(mt_rand(0, 255));
        }
    }
    return wordwrap(substr(bin2hex($r), 0, $length), $space, $sep, true);
}

Upvotes: 5

TimWolla
TimWolla

Reputation: 32701

Use a cryptografic hash-function. They output hex by default:

md5(rand()) // eg: ccc4fd993dd07dac621455c7c924d38f

Otherwards implode the return value of str_split(md5(rand()), 4) with colons to create something like this:

implode(':', str_split('ccc4fd993dd07dac621455c7c924d38f', 4));
// ccc4:fd99:3dd0:7dac:6214:55c7:c924:d38f

Depending on how many blocks you want to have random use substr to truncate the hash.


Note that this method does not create real randomness. If need need really random data have a look at the answer of Baba.

Upvotes: 2

user925885
user925885

Reputation:

You could generate a random number between 0 and 65 535 (0xffff) and then convert it into hex using dechex.

Note that the end of your string, nc21, is not a valid hexnumber, and therefore not a valid IPv6 address.

Upvotes: 1

Related Questions