Home > Backend Development > PHP Tutorial > PHP's most powerful random string generation function

PHP's most powerful random string generation function

angryTom
Release: 2023-04-07 15:54:01
forward
2492 people have browsed it

In PHP, especially website programs, it is often necessary to generate random passwords or strings, such as WeChat tokens, API keys, AppSecret, etc. Use the following random string generation function to easily generate what you need random string.

The code is as follows:

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length=6, $type='string', $convert=0){
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );
     
    if(!isset($config[$type])) $type = 'string';
    $string = $config[$type];
     
    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string{mt_rand(0, $strlen)};
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}
Copy after login

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of PHP's most powerful random string generation function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:www.whmblog.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template