PHP Tricks
September 10, 2022

How to generate random string in PHP?

The simplest way is using bin2hex function:

<?php
$str_len = 8;
$random_string = bin2hex(random_bytes($str_len));

echo $random_string;

PHP online sandbox

The another function is base64_encode. Use it when you don't care about special characters.

<?php

$str_len = 8;
echo base64_encode(random_bytes($str_len));

PHPize.online