Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

Answer for common case: no - you can't prevent this, since AJAX is just an HTTP-request. It can be sent no matter how you'll protect your server. So if the point is - to protect from 'evil hackers' - there's no way to do this. The correct though is to check/validate anything on server side.

But is it's about only basic check, you can read

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest')

-but be aware - this is also a data, which came from client i.e. it can't be trusted (actually, it's just HTTP-request header, nothing more)

Solution 3:

I think you can create a Session variable when the user logs in your aplication and check if this variable has the correct value whe you post something to your 'check.php' file to check if your user is previous authenticate

Solution 4:

Missing a lot of info but conceptually I am not sure you are worrying about a real risk. Bottom line is that people can use your form to check if emails exist so it's logical they can use check.php as well. Would be overkill to try and prevent that.

Solution 5:

I have one think - you can generate some unique token, store it on SESSION before show the page. Than on each checking you must to add this token to request. check.php must regenerate token and return it new.

But each request can emulate and it not protect you from people, which want to know results of check.php. Nothing protect...

Also you can make mechanism for analyzing ip request for checking

Post a Comment for "How To Authenticate An Ajax Request To A Php File?"