PHP function to generate random password string

This is a great function to generate a random string of text. I use it for everything from automating the creation of passwords to generating mailing list unsubscribe id’s. The length of the string is determind by the variable $length. If you have any trouble using it please let me know.

<?php
function generate_rid($length=9)
{
$randomid = "";

//characters allowed
$allowed = "0123456789bcdfghjkmnpqrstvwxyz";

$i = 0;
// Loop until password string is the required length
while ($i < $length) 	{  		

// Select random character allowed string
$char = substr($allowed, mt_rand(0, strlen($allowed)-1), 1);

// Add random character to password string
$randomid .= $char;
$i  ; }	

// Return random password
return $randomid;

}

// Output - Use whatever length you want
print generate_rid($length=10);
?>


Download: Generate a random string with PHP
Description: Random string with PHP.
Author:InterNoetics
Category: PHP code
Date: December 20, 2009

If you liked this article, you may also like:

  1. PHP function to truncate text (into a preview or excerpt) with trailing dots…
  2. Wrap a long string, word or URL over multiple lines with a PHP function
  3. Generate a Word Cloud from database values or array using PHP
  4. Randomly select rows from a LARGE database with MySQL
  5. PHP Function to Force Links to Open in a New Window
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*