I want to add the CSRF token to each POST request made on the login page.
I am new to PHP and tried implementing CSRF token but my page doesn't load because of my silly mistakes. I want to make vulnerable SQLi page with CSRF protection that is why I am trying to write vulnerable code. I want to add CSRF token to this page. My login page is working as expected just want to add CSRF.
<?php
session_start();
if($_POST['submit']) {
include_once('connection.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$sql = "SELECT id,username,password FROM users where username =
'$username' LIMIT 1";
$query = mysqli_query($db, $sql);
if($query) {
$row = mysqli_fetch_row($query);
$userId= $row[0];
$dbUserName = $row[1];
$dbPassword = $row[2];
}
if($username == $dbUserName && $password == $dbPassword) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('Location: user.php');
}
else {
echo "<b><i>Incorrect credentials</i><b>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Login</h1>
<form method="post" action="index.php">
<input type="text" name = "username" placeholder="Enter username">
<input type="password" name="password" placeholder="Enter password here">
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
If the token is valid then the user is allowed to log in the application else give an error "Token is not valid". In case the token is correct then the user will move to the new page.