Detecting Ajax in PHP and making sure request was from my own website Detecting Ajax in PHP and making sure request was from my own website ajax ajax

Detecting Ajax in PHP and making sure request was from my own website


Let you Controller

  • generate access token
  • store in session for later comparison

In your View

  • declare the access token as JS variable
  • send the token with each request

Back in your Controller

  • validate HTTP_X_REQUESTED_WITH
  • validate token

Check these security guidelines from OpenAjax.
Also, read the article on codinghorror.com Annie linked.


You can check the HTTP_REFERRER, but not all browsers set it. The best way is to write a wrapper for your ajax calls on the JavaScript side which sends part of document.cookie back to the server--only your domain has access to the cookie. You can compare the cookie in the request headers with the cookie in the AJAX call in php.

In response to, "does it even matter, these days"--YES, it does! Read this.


Regarding your last question: "Does it even matter, in these days?"This is a case by case question. If the ajax request is doing something that does not require security (e.g. loading latest stock quotes) then it really doesn't matter IMHO. If the request is loading information that should be secured (e.g. returning identifying information or doing something on the server) then you should treat it as such.

I personally don't use the server variables to know when something is an ajax request. Instead I just add a query parameter to the ajax call (e.g. http://domain.com/?ajax=true). If I need to secure the ajax call then I would use the same methods as securing a regular page request (using both client and server). As Lucas Oman pointed out, anything on the client side can be faked. Bottom line don't trust any request even if you think it is coming from your site or database. Always follow the mantra "filter input - escape output".