• Home
  • Shell
    • Emacs
    • Perl
    • screen
    • sed
  • Ubuntu
    • VNC
  • Web Development
    • Javascript
    • Joomla
    • MySQL
    • osTicket
  • Windows
    • Gimp

Web Dev> PHP created random password

Jul22
2011
Written by Scott Rowley
<?php
// The letter l (lowercase L) and the number 1
// have been removed, as they can be mistaken
// for each other.
function RandomPass() {
// Comment the first line to exclude special characters
$chars = "!@#$%^&*";
$chars .= "abcdefghijkmnopqrstuvwxyz023456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
srand((double)microtime()*1000000);
$i = 1;
$pass = '' ;
// Number of digits we'd like to have our password be
$n = 8;
while ($i < $n) {
$num = rand() % strlen($chars);
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
// Usage
$password = RandomPass();
echo "Random password is: $password";
?>
Posted in Web Development - Tagged create, dev, development, microtime, password, php, rand, random, return, srand, substr, web, while
« osTickets> Reports v5.0
» Media> Shoutcast ‘No such file or directory’

2 Comments

  1. Guy Scharf's Gravatar Guy Scharf
    July 28, 2011 at 10:04 am

    I’m just learning PHP for use with osTicket and reading some of your code as examples. I am finding your postings very useful.

    In this one, shouldn’t the phrase “rand() % 33” be “rand() % strlen($chars)” so that the random character is selected from the entire list of available characters? With 33, the passwords are always lower case in your example.

    • Scott Rowley's Gravatar Scott Rowley
      July 28, 2011 at 10:09 am

      Oops! Yes, thank you. It was originally 33 characters long but I added more options including the capitals and forgot to update that as well.

      Thanks!

Corrections? Questions? Comments?

Find an error?
Everything work out great for you?
Have some feedback?
Like to see something added to the article?

PLEASE leave us a comment after the article and let us know how we are doing, or if something needs corrected, improved or clarified.

Thank you!
- The Management

Advertisement

Sudo Bash
By Geeks - For Geeks

Back to Top