wp_generate_password

函数
wp_generate_password ( $length = 12, $special_chars = true, $extra_special_chars = false )
参数
  • (int) $length Optional. The length of password to generate. Default 12.
    Required:
    Default: 12
  • (bool) $special_chars Optional. Whether to include standard special characters. Default true.
    Required:
    Default: true
  • (bool) $extra_special_chars Optional. Whether to include other special characters. Used when generating secret keys and salts. Default false.
    Required:
    Default: false
返回值
  • (string) The random password.
定义位置
相关方法
wp_ajax_generate_passwordwp_set_passwordgenerate_random_passwordwp_ajax_nopriv_generate_passwordwp_generator
引入
2.5.0
弃用
-

wp_generate_password: 这个函数用来生成一个指定长度的随机密码。它把密码的长度作为一个参数,并返回生成的密码。

从定义的字符集中生成一个随机密码。

使用wp_rand()来创建密码,其可预测性远远低于类似的本地PHP函数如`rand()`或`mt_rand()`。

function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		if ( $special_chars ) {
			$chars .= '!@#$%^&*()';
		}
		if ( $extra_special_chars ) {
			$chars .= '-_ []{}<>~`+=,.;:/?|';
		}

		$password = '';
		for ( $i = 0; $i < $length; $i++ ) {
			$password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
		}

		/**
		 * Filters the randomly-generated password.
		 *
		 * @since 3.0.0
		 * @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters.
		 *
		 * @param string $password            The generated password.
		 * @param int    $length              The length of password to generate.
		 * @param bool   $special_chars       Whether to include standard special characters.
		 * @param bool   $extra_special_chars Whether to include other special characters.
		 */
		return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars );
	}
endif;

if ( ! function_exists( 'wp_rand' ) ) :
	/**
	 * Generates a random non-negative number.
	 *
	 * @since 2.6.2
	 * @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available.
	 * @since 6.1.0 Returns zero instead of a random number if both `$min` and `$max` are zero.
	 *
	 * @global string $rnd_value
	 *
	 * @param int $min Optional. Lower limit for the generated number.
	 *                 Accepts positive integers or zero. Defaults to 0.
	 * @param int $max Optional. Upper limit for the generated number.
	 *                 Accepts positive integers. Defaults to 4294967295.
	 * @return int A random non-negative number between min and max.
	 */

常见问题

FAQs
查看更多 >