PHP CSRF Token

PHP

Generating a CSRF Token

Commonly this token is generated at the very top of a file with "session_start()" before it, so the CSRF token session variable works:

Its good to add this on top of your file, so the page detects that this function is present.

Injecting CSRF Token to Input

After you have created the token maker, put the session variable into a hidden input:

You can put whatever you want for the hidden input's name, but the token being passed into "value" attribute is mandatory.

Validating CSRF Token

Token passed into a hidden input, begin validating it in PHP:

If this validation of cross-site request forgery token fails, the page litteraly dies - user has to retry.

Full CSRF App Instance

Using the above 3 examples, we can combine it into a full working system:

On the form, use the "action" attribute or JavaScript to send form data for PHP to process.