from the yii2 framework
/** * Generates a random string of specified length. * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding. * * @param int $length the length of the key in characters * @return string the generated random key */ function generateRandomString($length = 10) { $bytes = random_bytes($length); return substr(strtr(base64_encode($bytes), '+/', '-_'), 0, $length); }