This is a simple, framework-agnostic library that helps you protect your PHP web apps from CSRF attacks. CSRF Shield is built on the idea of sending tokens with the POST method only; otherwise the server will respond with a 405
status code (Method Not Allowed
).
Remember: It is encouraged not to disclose CSRF tokens in URLs. For further information on disclosing tokens in URLs, please visit OWASP's Cross-Site Request Forgery CSRF Prevention Cheat Sheet.
Via composer:
$ composer require programarivm/csrf-shield
Make sure that a PHP session is been started already and then use a CsrfShield\Protection
object as it is shown below.
To create/store a new CSRF token into the session:
<?php
use CsrfShield\Protection;
session_start();
// ...
(new Protection)->startToken();
To protect a PHP code snippet that responds to a POST request:
<?php
use CsrfShield\Protection;
session_start();
// ...
(new Protection)->validateToken();
Creates and stores a new CSRF token into the session.
(new Protection)->startToken();
Side Note: The name of the CSRF session variable is
_csrf_shield_token
by default.
Gets the current CSRF token from the session.
(new Protection)->getToken();
Validates the incoming CSRF token against the current session's token.
(new Protection)->validateToken();
The token can be read either through $_POST['_csrf_shield_token']
, or through $_SERVER['HTTP_X_CSRF_TOKEN']
if an AJAX call is made with an X-CSRF-Token
header.
If the token is not valid the server will send a 403
response (Forbidden
).
HTML input tag with the embedded value of the current CSRF token.
(new Protection)->htmlInput();
Here is an example:
<input type="hidden" name="_csrf_shield_token" id="_csrf_shield_token" value="5b18469018952acd17039f62f310426ceac16d3f" />
The GNU General Public License.
Would you help make this library better? Contributions are welcome.
- Feel free to send a pull request
- Drop an email at [email protected] with the subject "CSRF Shield Contributions"
- Leave me a comment on Twitter
- Say hello on Google+
Many thanks.