Skip to content

Instantly share code, notes, and snippets.

@olivertappin
Created October 10, 2016 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olivertappin/3e2f20ae8e197fe6f64594c0d59107f0 to your computer and use it in GitHub Desktop.
Save olivertappin/3e2f20ae8e197fe6f64594c0d59107f0 to your computer and use it in GitHub Desktop.
Generate a random string in PHP 5.6 using mt_rand
<?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