PHP – Random string generator snippet

This is a little function that I use all the time to generate random strings. There are 3 options for random strings with this: Alpha, Alpha-numeric, and Alpha-numeric with symbols. This is important because sometimes it’s a good idea not to allow special characters in a php string. However, the special characters are great if you need to create a key or initialization vector for 2 way encryption.

This can be used to generate random passwords or keys or just about anything else that needs a random string. You can also throw this directly into a class and use it as a static method.

 * Generate a random string
 * @param int $length
 * @param int $mode 1 = Alpha, 2 = Alpha-numeric, 3 = Alpha-numeric with symbols
 * @param boolian $char_set Set true for Upper and Lower case letters
 * @return string 
function random_string($length=16,$mode=1,$char_set=false)
	$string = '';
	if($char_set) {
		$possible .= strtolower($possible);
	switch($mode) {
		case 3:
			$possible .= '`~!@#$%^&*()_-+=|}]{[":;<,>.?/';
		case 2:
			$possible .= '0123456789';
	for($i=1;$i<$length;$i++) {
		$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
		$string .= $char;
	return $string;


echo random_string(32);
echo random_string(16,2,true);
echo random_string(16,3);
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  1. Myke Hines 24 Jul, 2009

    Why not just use uniqid() for alpha numeric?

  2. jestep 24 Jul, 2009

    There’s no way to control length with uniqid(). Otherwise if you’re going to hash it, uniqid() should work fine.

  3. jestep 24 Jul, 2009

    Another good way to do it is with the chr() function using characters 33-126 and (128-255?). The problem here is that you need to use escape characters: 92 (\) and/or 34,44 (” and ‘).

Copyright © 2024 SayNoToFlash, Jamie Estep, All Rights Reserved · Theme design by Themes Boutique