mahdy/wpnonce

以面向对象的方式运行 WordPress Nonce

1.0.0 2017-11-29 20:54 UTC

This package is not auto-updated.

Last update: 2024-09-20 02:00:39 UTC


README

以面向对象的方式使用 WordPress Nonce

用法

此包用于替代 WordPress 中的 wp_nonce_*() 函数。它以面向对象的方式构建,并使代码更易读。

环境

已测试与 WordPress v4.9 兼容。

安装

通过直接 composer 命令

composer require mahdy/wpnonce

或通过编辑 composer.json 文件,然后使用 composer update

{
    "require": {
        "mahdy/wpnonce" : "1.0.0"
    }
}

如何使用

此包用于生成和验证 WordPress Nonce。

设置操作

1- 通过构造函数

$nonce =  new \WpNonce\Nonce("Xaction");

2- 通过设置函数

$nonce =  new \WpNonce\Nonce();
$nonce->setAction("Xaction");

设置名称(可选)

它用于 URL 和表单字段。默认值为 "_wpnonce"

$nonce->setName("theNewName");

生成 Nonce 字符串

1- 显式地

/*if you didn't set the action in constructor, you have to use setter before to use this function*/
$nonce_string = $nonce->generateNonce();

2- 作为字符串

/*use the object directly */
$str = "the following object will return as Nonce string ".$nonce;

生成 Nonce URL

$url = "https://somewebsite.com/";
$nonce_url = $nonce->generateNonceUrl($url);

在表单中生成 Nonce 字段

它接受 2 个可选参数:generateNonceField($referer = true, $echo = true)

$nonce_HTML_input = $generateNonceField()

验证 Nonce 字符串

如果最后 12 小时内生成,则返回 1;如果最后 24 小时内生成,则返回 2

if (\WpNonce\NonceVerifier::verify($nonce, $action)) {...}

验证提交的 Nonce

使用 checkAdminReferer($action, $input_name = "_wpnonce") 函数进行验证。

if (\WpNonce\NonceVerifier::checkAdminReferer($action)) {...}

验证 Ajax 请求

函数 checkAjaxReferer($action, $arg_name = false, $die = true) 有 2 个可选参数。

if (\WpNonce\NonceVerifier::checkAjaxReferer($action)) {...}

运行单元测试

1- 首先,您需要安装 PHPUnit

2- 打开包文件夹:vendor/mahdy/wpnonce 切换到此目录以运行 phpunit

3- 在运行之前,更改 vendor/mahdy/wpnonce/bootstrap.php 并将 WORDPRESS_PATH 更改为您的 WordPress 安装目录。

4- 从包目录中,在命令行中运行

$ phpunit