Onglo Onglo - 1 year ago 60
MySQL Question

PHP random_bytes returns unreadable characters

I am using:


to generate a random string for my program. This string is then stored in a mysql database. However, when I run the function, I get an output such as


which includes unreadable characters. When I then try to store it in my database, the � characters are not stored and so this means that the string is not properly preserved.

How can I make it so that it returns a string with only readable characters that will not be lost in my mysql database?


Answer Source

random_bytes generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors. use like this

$bytes = random_bytes(5);
echo bin2hex($bytes);

you can also write your own code to generate the random string of a specific length

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
echo $randomString;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download