In this blog post, you will learn how to prevent the cross site request forgeries in the PHP.
Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF.
Here the hacker submits the forms internally by using automation tools to spam the websites or applications, So to get rid of this type of unauthorized submission by attackers we have to use some rules in PHP. Here you need to send the token keys by users which are generated randomly and saved in the session variable.
How to Prevent CSRF in Core PHP
Step-1: Generate Random Token by using
mt_rand()
and Encrypt it by using md5()
1 2 3 4 5 6 | <?php session_start(); echo $_SESSION['token'] = md5(uniqid(mt_rand(), true)); ?> |
Step-2: Send this token to Server page by hidden input field inside the form.
1 | <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" /> |
Step-3: Validate it using PHP
1 2 3 4 5 6 7 8 | <?php session_start(); if ($_POST['token'] != $_SESSION['token'] || !isset($_SESSION['token'])){ echo 'Unauthorised Form Submitted'; }else { echo 'Authorised form submitted'; } ?> |
Now we can combine all the code
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 | <?php session_start(); echo $_SESSION['token'] = md5(uniqid(mt_rand(), true)); ?> <div class="wrapper col-sm-4"> <form action="" method="POST"> <div class="form-group"> <label class="control-label col-sm-4" for="textinput">Name</label> <div class="col-sm-8"> <input id="textinput" name="name" class="form-control input-md" required="" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="textinput">Email</label> <div class="col-sm-8"> <input id="textinput" name="email" class="form-control input-md" required="" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="textinput">Phone</label> <div class="col-sm-8"> <input id="textinput" name="phone" class="form-control input-md" required="" type="text"> </div> </div> <div class="form-group"> <div class="col-sm-8"> <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" /> <input type="submit" value="Submit" /> </div> </div> </form> </div> <?php session_start(); if ($_POST['token'] != $_SESSION['token'] || !isset($_SESSION['token'])) { echo 'Unauthorised Form Submitted'; } else { echo 'Authorised form submitted'; } ?> |
So this code can prevent hackers to submit forms internally, he needs to know the token code saved in session before submitting the forms.