Welcome to Server Circle. It's a friendly site and all levels of experience are welcome. Be aware that we use cookies for your login.
Server Circle - Ask questions about Servers and get answers from experts.
Beta (0.03 sec)
Generating a random number for a code in PHP

How would I generate say eight digits out of a specific set of characters (not password characters) in PHP ?

I want something random like:

4g3045js

from alphanumberic characters only ideally.
Asked by:
Shrek
513 points
 Report Abuse
 Share Page - Category: Programming - Tags: Generating a random number for a code in PHP
 Enter your response
Please use Pastie.org to paste lengthy code or to fix formatting issues with code
  • Responses in reverse (3)

Best Answer

This example will echo a 8 digit random number to screen

<?php

echo substr(mt_rand(),0,8);

?>


Response by:
apjone
1478 points
Thanks very much.

Response by:
Shrek
513 points
Here's a short example to generate alphanumeric codes. Changing the string passed to str_split alone will let you use an arbitrary set of characters.

<?php

$charset=str_split("0123456789abcdefghijklmnopqrstuvwxyz");

$output="";

for($i=0;$i<8;$i++){

$output.=$charset[rand(0,count($charset)-1)];

}

echo $output;

?>


Response by:
jercos
29 points


  • Related Questions
About Us : Contact Us : Etiquette : Terms : CDN Failover : ShorterURL : CDN Fallback : © 2013 Server Circle