I use my PHP back-end to detect AJAX requests by checking for a value in $_SERVER['HTTP_X_REQUESTED_WITH']
.
This gives me a reliable detection, making sure the request is made utilizing AJAX techniques.
How can I make sure the request came from my own domain, and not an external domain/robot?
www.example.com/ajax?true could allow anyone to make an AJAX call and cut the information.
I could make sessions for everyone that enters my website normally, and then allow AJAX calls.. but that can be faked too.
Does it even matter these days?
Let you Controller
In your View
Back in your Controller
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".
Really, the most secure way to do this is to, as you suggested, use server-side sessions, as these cannot be crafted as cookies can.
Granted, someone can still hijack a session ID, but if you also store the user's IP address in their session and check it on each request, you can weed out a lot of hijacks. Only someone on the same LAN or proxy could hijack it.
Any other method mentioned--cookies, javascript, http referer--depends on client-side data, which is insecure and should always be suspected of being fake, forged, hijacked and maliciously constructed.
Use POST session secured requests:
Inside the Webpage (e.g. index.php) we need to store the sessionid
The ajax requests (ajaxrequest.js)
Responsible php side:
David Walsh has a good solution