Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ajax

security

php

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?

like image 652
Yossi Avatar asked Dec 23 '09 16:12

Yossi


People also ask

How do I know if AJAX request is successful?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

Can AJAX be used with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.


1 Answers

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.

like image 53
Gordon Avatar answered Sep 17 '22 05:09

Gordon