Example of generating random password of verification code implemented by php and JS

  • 2021-12-12 03:58:05
  • OfStack

This paper illustrates the function of generating random password (verification code) implemented by php/JS. Share it for your reference, as follows:

PHP writing:


//A-Z a-z 0-9 !#$%^&*
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%^&*";
// Generate random characters 
function createPwd($str,$len){
  $pwd = '';
  $strlen = strlen($str);
  for($i=0;$i<$len;$i++){
    $pwd .= $str{mt_rand(0,$strlen-1)};
  }
  return $pwd;
}
echo createPwd($str,16);

Run results:

TX!kXjmpZeHS7GOO

js writing


//A-Z a-z 0-9 !#$%^&*
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%^&*";
// Generate random characters 
function createPwd(str,len){
  var pwd = '';
  var maxPos = str.length;
  for(var i=0;i<len;i++){
    pwd += str.charAt(Math.floor(Math.random()*maxPos));
  }
  return pwd;
}
var passwd = createPwd(str,16);
document.write(passwd);

Use the online HTML/CSS/JavaScript code running tool http://tools.ofstack.com/code/HtmlJsRun to test the above JS code, and the running results are as follows:

%^NceAuKz^g$fSdS

PS: Here are two online tools with similar functions for your reference:

Online random number/string generation tool:
http://tools.ofstack.com/aideddesign/suijishu

Online random character/random password generation tool:
http://tools.ofstack.com/aideddesign/rnd_password

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of PHP Mathematical Operation Skills", "Summary of php String (string) Usage", "PHP Data Structure and Algorithm Tutorial", "Summary of php Programming Algorithm", "Encyclopedia of PHP Array (Array) Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: