- bin2hex: documentation ( source)
- chr: documentation ( source)
- mt_rand: documentation ( source)
- function_exists: documentation ( source)
- base64_encode: documentation ( source)
- hexdec: documentation ( source)
- define: documentation ( source)
<?php
if (!defined('PHP_EOL')) {
define('PHP_EOL', "\r\n");
}
// generate the 32bit byte array (if you have the "openssl_random_pseudo_bytes" function available)
if (function_exists('openssl_random_pseudo_bytes')) {
$random_key = openssl_random_pseudo_bytes(32);
} else {
// this is the longer way to do it...
$random_key = '';
for( $i = 0; $i < 64; $i++) {
$random_key .= ((bool)mt_rand(0, 1) ? chr(mt_rand(65, 90)) : mt_rand(0, 9));
}
$random_key = hexdec($random_key);
}
// this is it as hex
print "Hex key: " . bin2hex($random_key) . PHP_EOL;
print PHP_EOL;
// this is the base64 string that you want to save
print "Save this string: " . base64_encode($random_key) . PHP_EOL;