wp_is_site_protected_by_basic_auth()
云策文档标注
概述
wp_is_site_protected_by_basic_auth() 函数用于检查当前站点是否受到 HTTP Basic Auth 保护。它通过检测 $_SERVER['PHP_AUTH_USER'] 和 $_SERVER['PHP_AUTH_PW'] 是否存在来判断,并支持基于上下文(如登录、管理、前台)的检查。
关键要点
- 函数返回布尔值,表示站点是否受 Basic Auth 保护。
- 接受可选参数 $context,可指定为 'login'、'admin' 或 'front',默认为当前上下文。
- 目前仅通过检查 Basic Auth 凭据存在性来判断,在不同上下文中调用可能不准确,未来版本可能改进。
- 主要用于 Application Passwords 功能,以避免与 Basic Auth 冲突。
- 提供过滤器 wp_is_site_protected_by_basic_auth 用于自定义检查逻辑。
代码示例
function wp_is_site_protected_by_basic_auth( $context = '' ) {
global $pagenow;
if ( ! $context ) {
if ( 'wp-login.php' === $pagenow ) {
$context = 'login';
} elseif ( is_admin() ) {
$context = 'admin';
} else {
$context = 'front';
}
}
$is_protected = ! empty( $_SERVER['PHP_AUTH_USER'] ) || ! empty( $_SERVER['PHP_AUTH_PW'] );
/**
* Filters whether a site is protected by HTTP Basic Auth.
*
* @since 5.6.1
*
* @param bool $is_protected Whether the site is protected by Basic Auth.
* @param string $context The context to check for protection. One of 'login', 'admin', or 'front'.
*/
return apply_filters( 'wp_is_site_protected_by_basic_auth', $is_protected, $context );
}注意事项
- 当前实现仅检查 Basic Auth 凭据是否存在,在不同上下文(如非当前请求)中调用可能返回不准确结果,需谨慎使用。
- 此函数自 WordPress 5.6.1 版本引入。
原文内容
Checks if this site is protected by HTTP Basic Auth.
Description
At the moment, this merely checks for the present of Basic Auth credentials. Therefore, calling this function with a context different from the current context may give inaccurate results.
In a future release, this evaluation may be made more robust.
Currently, this is only used by Application Passwords to prevent a conflict since it also utilizes Basic Auth.
Parameters
$contextstringrequired-
The context to check for protection. Accepts
'login','admin', and'front'.
Defaults to the current context.
Source
function wp_is_site_protected_by_basic_auth( $context = '' ) {
global $pagenow;
if ( ! $context ) {
if ( 'wp-login.php' === $pagenow ) {
$context = 'login';
} elseif ( is_admin() ) {
$context = 'admin';
} else {
$context = 'front';
}
}
$is_protected = ! empty( $_SERVER['PHP_AUTH_USER'] ) || ! empty( $_SERVER['PHP_AUTH_PW'] );
/**
* Filters whether a site is protected by HTTP Basic Auth.
*
* @since 5.6.1
*
* @param bool $is_protected Whether the site is protected by Basic Auth.
* @param string $context The context to check for protection. One of 'login', 'admin', or 'front'.
*/
return apply_filters( 'wp_is_site_protected_by_basic_auth', $is_protected, $context );
}
Hooks
- apply_filters( ‘wp_is_site_protected_by_basic_auth’, bool $is_protected, string $context )
-
Filters whether a site is protected by HTTP Basic Auth.
Changelog
| Version | Description |
|---|---|
| 5.6.1 | Introduced. |