-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathphtml-auto-nonce-name.php
69 lines (64 loc) · 2.03 KB
/
phtml-auto-nonce-name.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
require __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;
$nonce = null;
$isValidForm = false;
$isValidToken = false;
$wasSubmitted = filter_has_var(INPUT_POST, 'myform');
$inputNumber = filter_input(INPUT_POST, 'number') ?? '';
$tokenName = filter_input(INPUT_POST, 'token_name');
$tokenValue = filter_input(INPUT_POST, 'token_value') ?? '';
/**
* Instantiate the nonces manager using a files system cache.
*/
$manager = new NoncesManager(new FilesystemCache);
/**
* Validate the submitted token and remove the nonce.
*/
if ($tokenName) {
$isValidToken = $manager->verifyAndVerify($tokenName, $tokenValue);
}
if ($wasSubmitted && $isValidToken) {
$isValidForm = is_numeric($inputNumber);
}
/**
* Generate a nonce.
*/
if (!$wasSubmitted || (!$isValidForm && $isValidToken)) {
$nonce = $manager->create($tokenName);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Page Title</title>
</head>
<body>
<?php if ($nonce) : ?>
<?php if ($wasSubmitted && !$isValidForm) : ?>
<p>Invalid input!</p>
<?php endif; ?>
<form method="POST">
Number:
<input type="text"
name="number"
value="<?= $inputNumber ?>" />
<input type="hidden"
name="token_name"
value="<?= htmlspecialchars($nonce->getName()) ?>" />
<input type="hidden"
name="token_value"
value="<?= htmlspecialchars($nonce->getValue()) ?>" />
<input type="submit" name="myform" value="Submit" />
</form>
<?php elseif (!$isValidToken) : ?>
<p>Invalid token!</p>
<?php elseif ($isValidForm) : ?>
<p>Success! Resending the form will throw an error.</p>
<?php else : ?>
<p>Unexpected state!</p>
<?php endif; ?>
</body>
</html>