wp_nonce_tick()
云策文档标注
概述
wp_nonce_tick() 函数用于生成与时间相关的变量,以支持 WordPress 中 nonce(一次性令牌)的创建和验证。它基于过滤后的 nonce 生命周期计算一个整数值,确保 nonce 在指定时间窗口内有效。
关键要点
- 函数返回一个浮点值,向上取整为下一个最高整数,用于 nonce 的时间依赖性计算。
- nonce 的生命周期由 'nonce_life' 过滤器控制,默认值为 DAY_IN_SECONDS(一天,即 86,400 秒)。
- 从 WordPress 6.1.0 版本开始,添加了 $action 参数,允许针对特定操作进行更精细的过滤器调整。
- nonce 的实际有效时间可能为 nonce_life 值的一半到该值减一秒之间,具体取决于生成时间。
- 此函数被 wp_verify_nonce() 和 wp_create_nonce() 等核心函数调用,用于安全验证。
代码示例
function wp_nonce_tick( $action = -1 ) {
$nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS, $action );
return ceil( time() / ( $nonce_life / 2 ) );
}注意事项
- 使用 'nonce_life' 过滤器可以自定义 nonce 的生命周期,但需注意这会影响所有相关 nonce 操作的安全性。
- 在验证 nonce 时,应结合 wp_verify_nonce() 函数确保时间窗口内的有效性,避免安全漏洞。
原文内容
Returns the time-dependent variable for nonce creation.
Description
A nonce has a lifespan of two ticks. Nonces in their second tick may be updated, e.g. by autosave.
Parameters
$actionstring|intoptional-
The nonce action.
Default:
-1
Source
function wp_nonce_tick( $action = -1 ) {
/**
* Filters the lifespan of nonces in seconds.
*
* @since 2.5.0
* @since 6.1.0 Added `$action` argument to allow for more targeted filters.
*
* @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
* @param string|int $action The nonce action, or -1 if none was provided.
*/
$nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS, $action );
return ceil( time() / ( $nonce_life / 2 ) );
}
Hooks
- apply_filters( ‘nonce_life’, int $lifespan, string|int $action )
-
Filters the lifespan of nonces in seconds.
Skip to note 2 content
Roy Orbitson
The mathematics of this function actually only guarantees a nonce’s lifespan to be half of the
nonce_lifefiltered value but may be up to that value (minus 1 second), depending on the time of day it was generated.See my comment on verifying nonces.