Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active December 15, 2015 21:19
Show Gist options
  • Save jrobinsonc/5324883 to your computer and use it in GitHub Desktop.
Save jrobinsonc/5324883 to your computer and use it in GitHub Desktop.
Generate random strings. #strings #generator #php

Generate random string

Generate a random string with the specified length. Optionally you can set the chars to use for generate the string.

Usage

require 'generate_string.php';

// Normal usage:
printf('<p>Random string: %s</p>', generate_string('5'));

// Generating a password
printf('<p>Password: %s</p>', generate_string('8', '!@#$%:;=()-_/.?=abcdefghkmnpqrstuvwxyzABCDEFGHKMNPQRSTUVWXYZ0987654321!@#$%:;=()-_/.?='));
<?php
/**
* Generate random strings.
*
* @author JoseRobinson.com
* @link GitHup: https://gist.github.com/5324883
* @version 201304062359
* @param int $len
* @param string $chars (optional)
* @return string
*/
function generate_string($len, $chars = 'abcdefghijklmnopqrstuvwxyz0987654321')
{
$line = '';
for ($i = 1; $i <= $len; $i++)
{
$line .= $chars[mt_rand(0, (strlen($chars)-1))];
}
return $line;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment