Generate random passwords in PHP

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2008, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

Here is a function I wrote to generate a random string in PHP. It is probably most useful for generating passwords. You can specify the length of the resulting string, as well as what characters are allowed. The default length is eight and the default character set is alphanumeric.

function random_string($length = 8, $chars = null) {
  if (empty($chars)) $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  while (strlen($s) < $length) {
    $s .= substr($chars, rand(0, strlen($chars) - 1), 1);
  return $s;

// Usage
echo random_string(10);