Created
October 10, 2016 12:46
-
-
Save olivertappin/3e2f20ae8e197fe6f64594c0d59107f0 to your computer and use it in GitHub Desktop.
Generate a random string in PHP 5.6 using mt_rand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Strings | |
{ | |
/** | |
* Generate a secure random string | |
* | |
* @param $length | |
* @param string $characters | |
* @param string $encoding | |
* @throws \BadMethodCallException | |
* @return string | |
*/ | |
public static function random( | |
$length = 32, | |
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
$encoding = '8bit' | |
) { | |
if (0 === $length) { | |
throw new \BadMethodCallException('Please enter a length bigger than 0'); | |
} | |
if ('' === $characters) { | |
throw new \BadMethodCallException('Please enter some characters'); | |
} | |
if (false === ($max = mb_strlen($characters, $encoding))) { | |
throw new \BadMethodCallException('Invalid encoding passed'); | |
} | |
$string = ''; | |
$max--; | |
for ($i = 0; $i < $length; ++$i) { | |
$string .= $characters[mt_rand(0, $max)]; | |
} | |
return $string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment