Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active December 15, 2015 21:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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