How to prevent Cross-Site Request Forgery (CSRF) in PHP

A cross-site request forgery (CSRF) vulnerability occurs when:
A web application uses session cookies.
he application acts on an HTTP request without verifying that the request was made with the user’s consent.
If the request does not contain a nonce that proves its provenance, the code that handles the request is vulnerable to a CSRF attack (unless it does not change the state of the application.)  This means a web application that uses session cookies has to take special precautions in order to ensure that an attacker can’t trick users into submitting bogus requests.
For more details visit–
Generating CSRF Token

bin2hex(random_bytes(32)) —Generates cryptographically secure pseudo-random bytes.
string random_bytes ( int $length )
Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.
Verifying CSRF Token—-

Here is the full code —-

How to run  the script
1. Download and Unzip file on your local system.
2. Put this file inside root directory
3. Database Configuration
open browser type http://localhost/phpmyadmin
Create a database demos.
Import database tblcsrf.sql
Open Your browser put inside browser “http://localhost/csrf/”

Download Source Code(How to prevent Cross-Site Request Forgery (CSRF) in PHP)
Size: 2.88 KB
Version: V 1.0

Anuj Kumar

I'm Anuj kumar a web developer with 4+ year experience .I write blogs in my free time. I love to learn new technologies and share with others. I founded PHPGurukul in September 2015. The main aim of this website to is provide php , jquery , mysql , phpoops and other web development tutorials. I am trying best effort to make PHPGurukul useful for every single moment spend on this website. If you think this website is useful to visit please share with your friend and buddies.

Recommended Tutorials for you

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *