Professional Website Design Company UK
Support us Advertise Write for PM Design Submit Freebie Submit Your Website

Generate random string of characters in PHP

2
 
Posted on 13th Feb, 2010. Posted in:

Generate random string of characters in PHPIn this very short tutorial, I am going to show you how to ceate a flexible php function. This function will allow you to generate random string of your choosen characters and your choosen length. Let’s create the php function!
Demo

 

Starting our function

 
function random_string($chars, $length) {

Assigning strings to variables

 
// Assign strings to variables
$lc = ‘abcdefghijklmnopqrstuvwxyz’; // lowercase
$uc = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’; // uppercase
$nr = ‘1234567890′; // numbers
$sp = ‘^@*+-+%()!?’; //special characters

Creating switch for different chars selection

 
// Set cases for our characters
switch ($chars) {
case ‘lower’: $chars = $lc; break;
case ‘upper’: $chars = $uc; break;
case ‘numbers’: $chars = $nr; break;
case ’special’: $chars = $sp; break;
case ‘all’: $chars = $lc.$up.$nr.$sp; break;
}

You can specify more cases to suit your needs if it comes to character selection.

Processing (core of our function)

 
// Length of character list
$chars_length = (strlen($chars) – 1);
// Start our string
$string = $chars{rand(0, $chars_length)};
// Generate random string
for ($i = 1; $i < $length; $i = strlen($string))
{
// Take random character from our list
$random = $chars{rand(0, $chars_length)};
// Make sure the same two characters don’t appear next to each other
if ($random != $string{$i – 1}) $string .= $random;
}

Return variable

 
//return our generated string
return $string;
}

Echoing our function with different parameters

 
echo random_string(’lower’,20); // generates lowercase string – 20 chars length
echo random_string(’upper’,20); // generates uppercase string – 20 chars length
echo random_string(’numbers’,10); // generates numbers string – 10 chars length
echo random_string(’special’,40); // generates special chars string – 40 chars length
echo random_string(’all’,50); // generates all chars string – 50 chars length

Well, you’ve got the idea.

Feel free to share yours techniques to generate random string in php. Don’t forget to share it with others and subscribe to my newsletter!

Enjoyed this entry? Share it around!

 

Share it with others. Make others aware about web design tips, techniques and news.

 
 

You may also like to read

 
 
 
  • Dan

    Exactly what I was looking for! Thanks man!

  • http://www.google.com/ Teiya

    Thanks for sharing. Awayls good to find a real expert.

  •  
  •  
     
     
     
    Copyright © 2008 - 2012. All rights reserved.
    Pawel Martuszewski Design – Web Design Tutorials, operated by Direct Media Design