Use the for loop to traverse the defined characters.
The code is as follows: |
Copy code |
<? Php /* Generate Password * Length: 8 */ $ Str = "0123456789abcdefghijklmnopqrstuvwxyz"; // output character set $ N = 8; // output string length $ Len = strlen ($ str)-1; For ($ I = 0; $ I <$ n; $ I ++ ){ $ S. = $ str [rand (0, $ len)]; } Echo $ s. "<br/> "; ?>
|
It can generate a string of numbers, character strings, and so on.
(The combination of upper-case, lower-case, upper-case, and upper-case numbers can also be expanded based on your preferences ).
The following $ length = 5 is 10 digits if you change it to 10.
Change $ str = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz 'to $ str = '123', which is a pure numeric string.
The code is as follows: |
Copy code |
<? Php Function getRandStr ($ length ){ $ Str = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz '; $ RandString = ''; $ Len = strlen ($ str)-1; For ($ I = 0; $ I <$ length; $ I ++ ){ $ Num = mt_rand (0, $ len ); $ RandString. = $ str [$ num]; } Return $ randString; } // Use the following method: $ Test = getRandStr ($ length = 5 ); Echo $ test; ?> |
Or use the while
The code is as follows: |
Copy code |
<? Php /** */ Function createRandomStr ($ length ){ $ Str = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz '; // 62 characters $ Strlen = 62; While ($ length> $ strlen ){ $ Str. = $ str; $ Strlen + = 62; } $ Str = str_shuffle ($ str ); Return substr ($ str, 0, $ length ); } Echo createRandomStr (10 ); ?> |
The idea of array and character conversion is used:
The code is as follows: |
Copy code |
<? Php /** * @ Blog <www.111cn.net> */ Function createRandomStr ($ length ){ $ Str = array_merge (range (0, 9), range ('A', 'z'), range ('A', 'z ')); Shuffle ($ str ); $ Str = implode ('', array_slice ($ str, 0, $ length )); Return $ str; } Echo createRandomStr (10 ); ?> |