Skip to content

Instantly share code, notes, and snippets.

@nhtua
Last active October 21, 2016 09:26
Show Gist options
  • Save nhtua/7122489f8317a90c593b to your computer and use it in GitHub Desktop.
Save nhtua/7122489f8317a90c593b to your computer and use it in GitHub Desktop.
[php] Generate ramdom string
<?php
namespace Utils;
/**
* Class RandomStringGenerator
* @package Utils
*
* Solution taken from here:
* http://stackoverflow.com/a/13733588/1056679
*/
class RandomStringGenerator
{
/** @var string */
protected $alphabet;
/** @var int */
protected $alphabetLength;
/**
* @param string $alphabet
*/
public function __construct($alphabet = '')
{
if ('' !== $alphabet) {
$this->setAlphabet($alphabet);
} else {
$this->setAlphabet(
implode(range('a', 'z'))
. implode(range('A', 'Z'))
. implode(range(0, 9))
);
}
}
/**
* @param string $alphabet
*/
public function setAlphabet($alphabet)
{
$this->alphabet = $alphabet;
$this->alphabetLength = strlen($alphabet);
}
/**
* The safe way to genrate random string function.
* If you want to generate unique id, let use this function.
* @param int $length
* @return string
*/
public function generate($length)
{
$token = '';
for ($i = 0; $i < $length; $i++) {
$randomKey = $this->getRandomInteger(0, $this->alphabetLength);
$token .= $this->alphabet[$randomKey];
}
return $token;
}
/**
* The simple random function. Faster but maybe duplicated string.
* If you don't need to massive generate, you can use this function.
* @param Integer $length
* @return String has random content
*/
public function simple($length = 10) {
$randomString = '';
for ($i = 0; $i < $this->alphabetLength; $i++) {
$randomString .= $this->alphabet[rand(0, $this->alphabetLength - 1)];
}
return $randomString;
}
/**
* @param int $min
* @param int $max
* @return int
*/
protected function getRandomInteger($min, $max)
{
$range = ($max - $min);
if ($range < 0) {
// Not so random...
return $min;
}
$log = log($range, 2);
// Length in bytes.
$bytes = (int) ($log / 8) + 1;
// Length in bits.
$bits = (int) $log + 1;
// Set all lower bits to 1.
$filter = (int) (1 << $bits) - 1;
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
// Discard irrelevant bits.
$rnd = $rnd & $filter;
} while ($rnd >= $range);
return ($min + $rnd);
}
}
@nhtua
Copy link
Author

nhtua commented Apr 23, 2015

Please add more random, what you know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment