Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate an AJAX request to a PHP file?

On my website I have a registration page which makes an AJAX request to check if a username is available after it has been entered. This file is called check.php and is in the same directory as the registration.php file. When data is posted to check.php it will perform a query at a MySQL database and return how many users it found with that username.

If anybody were to post data to the check.php file they would see the result, too. I need to stop this somehow, I've read on a few answers I need to "authenticate" each request. This is probably a very large topic although I'm not too sure what to search for to find more about it. Is authenticating each request a good way to stop unnecessary username checks? If so I would really appreciate it if anyone could point me in the right direction as to how to do this.

like image 537
jskidd3 Avatar asked Nov 18 '25 06:11

jskidd3


1 Answers

A solution is to generate a unique token in session, and put it in all pages that will contain a form. Post this token on each AJAX request you make. It is called CSRF protection, Cross-Site Request Forgery.

You can add a protection layer checking the user referer in HTTP headers.

like image 82
netvision73 Avatar answered Nov 20 '25 19:11

netvision73



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!