3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Generate a random string, using a cryptographically secure * pseudorandom number generator (random_int) * * per https://stackoverflow.com/a/31107425 */ function get_random_string($length = 16, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { $str = ''; $max = mb_strlen($keyspace, '8bit') - 1; for ($i = 0; $i < $length; ++$i) { $str .= $keyspace[random_int(0, $max)]; } return $str; } // Tests. echo 'Test 01: ' . get_random_string() . "\n"; echo 'Test 02: ' . get_random_string(2) . "\n"; echo 'Test 03: ' . get_random_string(32) . "\n"; echo 'Test 04: ' . get_random_string(16, '1234567') . "\n"; echo 'Test 05: ' . get_random_string(16, '123abcABC') . "\n"; echo 'Test 06: ' . get_random_string(16, 'ABC') . "\n"; echo 'Test 07: ' . get_random_string(16, '10') . "\n";

preferences:
33.43 ms | 402 KiB | 5 Q