Home PHP JavaScript CSS WordPress APIs .htaccess Other How-To Useful Scripts What I Recommend
Posted on by Aleksandar Gichevski ()

Randomly created strings without specific pattern are best way for protection.

When u create your password is best way to be big random string including variety of letters and numbers.

Here is a function for generating random string depending from the entered length parameter.

function generate_random_string($length) 

	$generated_string = '';
	$last_char = 0; 
	$chosen_char = 0; 
	for($l=0; $l<$length; $l++) 
		while($chosen_char == $last_char) 
			 $chosen_char = rand(48, 109); 
			 if($chosen_char > 57) $chosen_char += 7; 
			 if($chosen_char > 90) $chosen_char += 6; 
			$generated_string .= chr($chosen_char); 
			$last_char = $chosen_char; 
	return $generated_string; 

Let’s explain the above function…

As input parameter we have $length which is the value how much we want the string length to be.

As defined parameters we have:

  • $generated_string - which in code body will accept the chosen characters
  • $last_char – remember the last chosen character so we don’t have 2 same characters in a row
  • $chosen_char – represents current chosen character

The FOR Loop generates 1 character at a time until he receives the value length, containing inside WHILE loop that checks if the new chosen character is same as the last character.

You are maybe asking what are these 2 lines for?

if($chosen_char > 57) $chosen_char += 7; 
if($chosen_char > 90) $chosen_char += 6; 

This function generates random string without any special characters and uses PHP chr() function to generate characters based from an ASCII Table.

So if u see the table below you will notice that with these 2 lines we are jumping the special characters in the Table and we give as result clean letter/number random string.

If you want the special characters to be included also in the random string you can modify this function very easily.


Here is example so you can test this function… Just enter string length you would like the system to generate.

Other Posts You Might Like

Get a fast, free website audit

Enter your URL below to get full in-depth SEO report and tips.

Useful Scripts

Most Popular Posts

Recent Posts

June 14th, 2014
Website Optimization Using Gzip Compression

June 10th, 2014
Google Search AutoComplete API

May 14th, 2014
What is a Tag Cloud and How to Calculate it by Formula

March 27th, 2014
Error writing file /tmp (errcode 28) Solved!

February 15th, 2014
Fixed CSS & HTML Navigation Bar

February 9th, 2014
Benchmark Your Server (CPU, File IO, MySQL) with SysBench

February 8th, 2014
JavaScript Array Basics

January 29th, 2014

January 25th, 2014
Payoneer Debit Card for Freelancers to receive money online

January 24th, 2014
How HTML Color Codes are generated?

Read Latest Posts directly on Facebook