PHP code example of pedroac / nonce

1. Go to this page and download the library: Download pedroac/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/ */

    

pedroac / nonce example snippets



Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;
use \pedroac\nonce\Form\HtmlNonceField;
use \pedroac\nonce\Form\NonceForm;

// this handles automatically the input and nonce management
$form = new NonceForm(
    'token', // the HTML input name
    new NoncesManager(
      new FilesystemCache // a \Psr\SimpleCache\CacheInterface implementation
    )
);
// this will be used to generate a HTML input element
$htmlField = new HtmlNonceField($form);

if ($form->isSubmittedValid()) {
  /**
   * handle the success:
   * - if all form input is valid, show success page;
   * - otherwise, show an error page and the form again;
   */
}

if ($form->isSubmittedInvalid()) {
  /**
   * handle failure:
   * - don't show the form again;
   * - show an error message;
   */
}

<form method="POST">
    <?= $htmlField 


Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;

$manager = new NoncesManager(new FilesystemCache);

$isValidToken = false;
$isValidForm = false;
$wasSubmitted = filter_has_var(INPUT_POST, 'myform');
$tokenName = filter_input(INPUT_POST, 'token_name');
$tokenValue = filter_input(INPUT_POST, 'token_value') ?? '';

if ($tokenName) {
    $isValidToken = $manager->verifyAndExpire($tokenName, $tokenValue);
}
if ($wasSubmitted && $isValidToken) {
    // validate input
}

if (!$wasSubmitted || (!$isValidForm && $isValidToken)) {
  $nonce = $manager->create();
}

 if ($nonce) : 


Symfony\Component\Cache\Simple\ArrayCache;
use \pedroac\nonce\NoncesManager;
use \pedroac\nonce\Random\HexRandomizer;

$manager = new NoncesManager(
    new ArrayCache(60),
    new HexRandomizer(32), // a \pedroac\nonce\Random implementation
    new \DateInterval('PT3H')
);

$user_id = $_SESSION['user_id'];
$tokenName = "{$user_id}_form";
$nonce = $manager->create($tokenName);

$form = new NonceForm(
    'token',
    new NoncesManager(
      new FilesystemCache
    ),
    filter_input_array(INPUT_GET) // use $_GET
);
bash
php -S localhost:8000