Implimentation of CSRF Token in PHP Ajax

How we add CSRF protection in ajax request when we do registration or login on website ?
I try to find this subject on stackoverflow but I couldn’t get exact answer as I want and sitepoiny is my first experience community where I came for knowledge or answer I want.
Whenever I trying to implement CSRF in ajax request first errors show from CSRF offcourse it is genuinely becouse both page is diffrent.

but in security views How we make ajax so secure via CSRF or Jquery in PHP Native.
How Implement Ajax CSRF in my code, please help me.

<?php
	//start a session
	session_start();

	//create a key for hash_hmac function
	if (empty($_SESSION['key']))
		$_SESSION['key'] = bin2hex(random_bytes(32));

	//create CSRF token
	$csrf = hash_hmac('sha256', 'this is some string: index.php', $_SESSION['key']);

	//validate token
	if (isset($_POST['submit'])) {
		if (hash_equals($csrf, $_POST['csrf'])) {
			echo "Your name is: " . $_POST['username'];
		} else
			echo 'CSRF Token Failed!';
	}
?>
<html>
	<head>
		<title>CSRF Tutorial by CPI</title>
	</head>
	<body>
		<form method="POST" action="index.php">
			<input type="text" name="username" placeholder="What is your name?" >
			<input type="hidden" name="csrf" value="<?php echo $csrf ?>">
			<input type="submit" name="submit" value="SUBMIT">
		</form>
	</body>
</html>

Hi HermioneGranger welcome to the forum

I’m confused as to how you envision AJAX being involved. AFAICT this is simply an expiring token being inserted into a form, the intent being to help ensure the form is being submitted by an authorized user.

eg.

  • I log in as me.
  • An expiring token is generated for my session.
  • When I go to a form to edit my account details, the token let’s the script know it’s me and not someone else.
  • If someone else tries to edit my details the token either doesn’t match or has expired and my account details won’t be edited.

How does what you want to do differ from this? In particular, the AJAX part.

1 Like

@Mittineague has replied to you, and you haven’t responded to his questions.

If you want help, then I suggest you clarify your question (rather than simply bumping the thread, which we don’t allow).

Actually I have confusion if I not add token function in my ajax form then anybody make simple form and do login on my website, So I want to protect this in this manner that my ajax url always accept my eebsite request and it only possible when we add token inside form.
If token of form(index.php) == token of ajax(call_ajax.php) then login/insert/update etc else {error : invalid tolen}
This is I want to say…

Sir in my post the code is correcf when we use PHP on same page of HTML page but what we do to same sdd this in Ajax Function ?