PHP code example of pinkcrab / wp-nonce

1. Go to this page and download the library: Download pinkcrab/wp-nonce library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pinkcrab / wp-nonce example snippets




use PinkCrab\Nonce\Nonce;

$nonce = new Nonce( 'my_action' );

// Get the current token.
$nonce->token();

// Render a <input type="hidden"> nonce field.
echo $nonce->nonce_field();

// Validate a submitted token.
if ( ! $nonce->validate( $_POST['_wpnonce'] ?? '' ) ) {
    wp_die( 'Invalid nonce' );
}

// Decorate a URL with the nonce token.
$url = $nonce->as_url( 'https://example.com/admin-action' );

$nonce = new Nonce( 'save_settings' );

$nonce = new Nonce( 'save_settings' );
echo $nonce->token(); // e.g. "31b31db189"

$nonce = new Nonce( 'url_action' );

$nonce->as_url( 'https://example.com/do' );
// https://example.com/do?_wpnonce=<token>

$nonce->as_url( 'https://example.com/do?id=42', 'my_nonce' );
// https://example.com/do?id=42&my_nonce=<token>

$nonce = new Nonce( 'form_submit' );

echo $nonce->nonce_field( 'settings_nonce' );
// <input type="hidden" id="settings_nonce" name="settings_nonce" value="<token>">

echo $nonce->nonce_field();
// <input type="hidden" id="_wpnonce" name="_wpnonce" value="<token>">

$nonce = new Nonce( 'my_action' );

$nonce->validate( $nonce->token() ); // true
$nonce->validate( 'anything_else' ); // false

$nonce = new Nonce( 'admin_save' );

if ( $nonce->admin_referer() ) {
    // OK to proceed.
}

$nonce    = new Nonce( 'serialised' );
$s_nonce  = serialize( $nonce );
$restored = unserialize( $s_nonce );

$restored->token() === $nonce->token(); // true