PHP Function to generate random / unique string or numbers str_random()

Learn to Programs random / unique string generator than can be how long you want. You can define your pool variable to choose specified characters.

By default this php function using predefined programs name 'openssl_random_pseudo_bytes' if this function is not available because of php version, then it will use your $pool variable to generate random string.

Source Code:

<?php
function str_random($length = 16)
    {
        if (function_exists('openssl_random_pseudo_bytes'))
        {
            $bytes = openssl_random_pseudo_bytes($length * 2);

            if ($bytes === false)
            {
                return 'Unable to generate random string.';
            }

            return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
        }

        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
    }

The use of str_random function to create random / unique ID like youtube.

Output / Usage:

<?php 

echo str_random(11);

//returns : xUtQqkboSQR

Comments: (Your feedback is valuable to us)