Prevent CSRF in PHP

Loading

To prevent csrf you should use token in form.

See the below code:

<?php
session_start();

if(isset($_POST['submit')){

if ($token && $_POST['token'] === $token) {

//Do the database insertion here

 

unset($_SESSION['token']);
}

}

$token = isset($_SESSION['my_token']) ? $_SESSION['my_token'] : "";
if (!$token) {

$token = md5(uniqid());
$_SESSION['my_token']= $token;
}
session_write_close();
?>
<html>
<body>
<form method="post" action=""><input type="text" name="name">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="submit" name="submit" value=" Submit" />

</form>
</body>
</html>


0 0 votes
Article Rating
Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x