{"id":33945364,"url":"https://github.com/pedroac/nonce4php","last_synced_at":"2026-04-08T19:32:49.536Z","repository":{"id":57037411,"uuid":"126977074","full_name":"pedroac/nonce4php","owner":"pedroac","description":"A nonce manager PHP library useful for preventing CSRF and replay attacks.","archived":false,"fork":false,"pushed_at":"2018-04-13T00:45:17.000Z","size":115,"stargazers_count":4,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-12-14T06:31:34.537Z","etag":null,"topics":["csrf-tokens","nonces","nonces-generator","php","php-library","replay-attack","security"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pedroac.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-03-27T11:36:29.000Z","updated_at":"2022-10-06T01:53:08.000Z","dependencies_parsed_at":"2022-08-23T19:40:07.568Z","dependency_job_id":null,"html_url":"https://github.com/pedroac/nonce4php","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/pedroac/nonce4php","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pedroac%2Fnonce4php","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pedroac%2Fnonce4php/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pedroac%2Fnonce4php/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pedroac%2Fnonce4php/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pedroac","download_url":"https://codeload.github.com/pedroac/nonce4php/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pedroac%2Fnonce4php/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31571600,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-08T14:31:17.711Z","status":"ssl_error","status_checked_at":"2026-04-08T14:31:17.202Z","response_time":54,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csrf-tokens","nonces","nonces-generator","php","php-library","replay-attack","security"],"created_at":"2025-12-12T17:46:32.245Z","updated_at":"2026-04-08T19:32:49.522Z","avatar_url":"https://github.com/pedroac.png","language":"PHP","funding_links":["http://paypal.me/pedroac"],"categories":[],"sub_categories":[],"readme":"# pedroac/nonce for PHP\n\n[![Build Status](https://travis-ci.org/pedroac/nonce4php.svg?branch=master)](https://travis-ci.org/pedroac/nonce4php)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/d099b114ef4f4d99bb1f39a8064aa8c4)](https://app.codacy.com/app/pedroac/nonce4php?utm_source=github.com\u0026utm_medium=referral\u0026utm_content=pedroac/nonce4php\u0026utm_campaign=badger)\n[![Support via PayPal](https://img.shields.io/badge/Donate-PayPal-green.svg)](http://paypal.me/pedroac)\n\nA [nonce](https://www.computerhope.com/jargon/n/nonce.htm) manager PHP library useful for preventing [CSRF](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) and [replay attacks](http://www.crypto-it.net/eng/attacks/replay.html).\n\nWe may find several articles and videos explaining the vulnerabilities that nonces try to prevent:\n- [YouTube - Jmaxxz - CSRF Explained](https://www.youtube.com/watch?v=vrjgD0azkCw)\n- [YouTube - Professor Messer - Cross-site Request Forgery](https://www.youtube.com/watch?v=rbP2jwEDlBM)\n- [YouTube - Professor Messer - Replay Attacks](https://www.youtube.com/watch?v=jy8USm8pIYM)\n- [YouTube - Hak5 - How to Hack Wireless Remotes with Radio Replay Attacks](https://www.youtube.com/watch?v=F3bISk5t8cA)\n- [Coding Horror - Preventing CSRF and XSRF Attacks](https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/)\n- [acunetix - CSRF Attacks, XSRF or Sea-Surf](https://www.acunetix.com/websitesecurity/csrf-attacks/)\n- [SitePoint - How to Prevent Replay Attacks on Your Website](https://www.sitepoint.com/how-to-prevent-replay-attacks-on-your-website/)\n\nIt seems, though, that many PHP nonces libraries are too restrictive, coupled with some framework, hard to use or hard to understand how they work.\n\n`pedroac/nonce` tries to solve those issues.\n\nIt allows choosing any [PSR-16](https://www.php-fig.org/psr/psr-16/) implementation to store temporarily the nonces, nonces values generators, expiration intervals and even a [`DateTime` provider](https://github.com/Kdyby/DateTimeProvider) to override the clock system (this feature is used for unit tests).\n\nIt also provides helpers to manage input, generate random nonces names and values, verify submitted tokens against the nonce and generate HTML elements.\n\n## Prerequisites\n\n- PHP 7.1 or later: http://php.net/downloads.php\n- Composer: https://getcomposer.org\n- At least one PSR-16 implementation. Examples:\n  - [symfony/cache](https://packagist.org/packages/symfony/cache)\n  - [matthiasmullie/scrapbook](https://packagist.org/packages/matthiasmullie/scrapbook)\n\n## Installing\n\nRun the command:\n\n`composer require pedroac/nonce`\n\n## Usage\n\n### Examples\n\n- [Using Symfony ArrayCache](php/examples/manager.php)\n- [CLI test](php/examples/cli-manager-test.php)\n- [HTML form using a session](php/examples/phtml-manager-test.php)\n- [HTML form using an auto generated nonce name](php/examples/phtml-auto-nonce-name.php)\n- [HTML form using a helper](php/examples/phtml-easy-form.php)\n\nThe HTML forms can be tested using a PHP built-in web server.  \nFrom the `php/examples` folder run the command:\n```bash\nphp -S localhost:8000\n```\nUse the URL http://localhost:8000/ in a browser.\n\n### HTML form with a token\n\n1) Create a nonce form helper:\n```php\n\u003c?php\nrequire __DIR__ . '/../vendor/autoload.php';\n\nuse Symfony\\Component\\Cache\\Simple\\FilesystemCache;\nuse \\pedroac\\nonce\\NoncesManager;\nuse \\pedroac\\nonce\\Form\\HtmlNonceField;\nuse \\pedroac\\nonce\\Form\\NonceForm;\n\n// this handles automatically the input and nonce management\n$form = new NonceForm(\n    'token', // the HTML input name\n    new NoncesManager(\n      new FilesystemCache // a \\Psr\\SimpleCache\\CacheInterface implementation\n    )\n);\n// this will be used to generate a HTML input element\n$htmlField = new HtmlNonceField($form);\n```\n\n2) Check if a valid token was submitted:\n```php\nif ($form-\u003eisSubmittedValid()) {\n  /**\n   * handle the success:\n   * - if all form input is valid, show success page;\n   * - otherwise, show an error page and the form again;\n   */\n}\n```\n\n3) Check if an invalid token was submitted:\n```php\nif ($form-\u003eisSubmittedInvalid()) {\n  /**\n   * handle failure:\n   * - don't show the form again;\n   * - show an error message;\n   */\n}\n```\n\n4) Implement the HTML form:\n```php\n\u003cform method=\"POST\"\u003e\n    \u003c?= $htmlField ?\u003e\n    \u003c!-- more HTML --\u003e\n    \u003cinput type=\"submit\" name=\"myform\" value=\"Submit\" /\u003e\n\u003c/form\u003e\n```\n\nThe nonce is expired automatically when the token is verified with the `NonceForm` class.\n\n### General usage\n\n1) Instantiate a nonce manager:\n```php\n\u003c?php\nrequire __DIR__ . '/../vendor/autoload.php';\n\nuse Symfony\\Component\\Cache\\Simple\\FilesystemCache;\nuse \\pedroac\\nonce\\NoncesManager;\n\n$manager = new NoncesManager(new FilesystemCache);\n```\n\n2) When a request is submitted, validate the submitted token and remove the nonce:\n```php\n$isValidToken = false;\n$isValidForm = false;\n$wasSubmitted = filter_has_var(INPUT_POST, 'myform');\n$tokenName = filter_input(INPUT_POST, 'token_name');\n$tokenValue = filter_input(INPUT_POST, 'token_value') ?? '';\n\nif ($tokenName) {\n    $isValidToken = $manager-\u003everifyAndExpire($tokenName, $tokenValue);\n}\nif ($wasSubmitted \u0026\u0026 $isValidToken) {\n    // validate input\n}\n```\n\n3) Generate a nonce when appropriate:\n```php\nif (!$wasSubmitted || (!$isValidForm \u0026\u0026 $isValidToken)) {\n  $nonce = $manager-\u003ecreate();\n}\n```\n\n4) Use the nonce name and value to build, for instance, a HTML form:\n```php\n\u003c?php if ($nonce) : ?\u003e\n  \u003cinput type=\"hidden\"\n        name=\"token_name\"\n        value=\"\u003c?= htmlspecialchars($nonce-\u003egetName()) ?\u003e\" /\u003e\n  \u003cinput type=\"hidden\"\n        name=\"token_value\"\n        value=\"\u003c?= htmlspecialchars($nonce-\u003egetValue()) ?\u003e\" /\u003e\n  \u003cinput type=\"submit\" name=\"myform\" value=\"Submit\" /\u003e\n\u003c?php endif; \u003e\n```\n\n### Options\n\nBesides the nonces cache storage, it's possible to select the random nonce value generator and the expiration interval: \n\n```php\n\u003c?php\nrequire __DIR__ . '/../vendor/autoload.php';\n\nuse Symfony\\Component\\Cache\\Simple\\ArrayCache;\nuse \\pedroac\\nonce\\NoncesManager;\nuse \\pedroac\\nonce\\Random\\HexRandomizer;\n\n$manager = new NoncesManager(\n    new ArrayCache(60),\n    new HexRandomizer(32), // a \\pedroac\\nonce\\Random implementation\n    new \\DateInterval('PT3H')\n);\n```\n\nIt's also possible to create a nonce with a specified name:\n\n```php\n$user_id = $_SESSION['user_id'];\n$tokenName = \"{$user_id}_form\";\n$nonce = $manager-\u003ecreate($tokenName);\n```\n\n`NonceForm` default input source is $_POST, but it accepts any array input:\n```php\n$form = new NonceForm(\n    'token',\n    new NoncesManager(\n      new FilesystemCache\n    ),\n    filter_input_array(INPUT_GET) // use $_GET\n);\n```\n\n## Running the tests\n\nRun from the library root folder:\n\n`php/vendor/bin/phpunit php/tests/ -c php/tests/configuration.xml`\n\nIf the tests were successful, `php/tests/coverage-html` should have the code coverage report.\n\n## Generating the HTML documentation\n\nRun from the library root folder:\n\n`sh scripts/generate-docs.sh`\n\nThe generated documentation should be inside the folder `docs`.\n\n## Versioning\n\nIt should be used [SemVer](http://semver.org/) for versioning.\n\n## Authors\n\n- Pedro Amaral Couto - Initial work - https://github.com/pedroac\n\n## License\n\npedroac/nonce is released under the MIT public license.  \nSee the enclosed [LICENSE](LICENSE) for details.\n\n## Acknowledgments\n\nThe library was developed as a private request response made by a Stackoverflow user.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpedroac%2Fnonce4php","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpedroac%2Fnonce4php","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpedroac%2Fnonce4php/lists"}