Skip to content

PHP Script to Prevent Cross-Site Request Forgery (CSRF) Attack in HTML5 Upload Form in Browser

index.php

<?php
session_start();
echo $_SESSION['token'] = md5(uniqid(mt_rand(), true));
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div  class="wrapper col-sm-4">
<form action="handler.php" 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" placeholder="Enter your name" class="form-control input-md" required="" type="text">
</div>
</div>    
<div class="form-group">
<label class="control-label col-sm-4" for="textinput">Age</label>  
<div  class="col-sm-8">
<input id="textinput" name="age" placeholder="Enter your age" 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" placeholder="Enter your 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 'Invalid Form Submitted';
} else {
// Write code to store data in database
echo 'Valid Form Submitted';
}
?>