Block PHP page to only show data if it is an AJAX request [duplicate]

4

I have a .php file that loads and displays all news from my database, I use this file to load the news dynamically with AJAX. So far so good, the user can usually go to the index.html page and see the news that has been uploaded via AJAX and PHP, but the user can also go to the noticias.php page and see all the news on the page. But I did not want this, did not PHP have to return data to AJAX or something like that? So that the user can not directly access the noticias.php ?

    
asked by anonymous 22.08.2014 / 20:47

2 answers

6

What you can check is relative to HTTP_X_REQUESTED_WITH

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
    AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    // se entrar aqui é uma chamada ajax
}
    
22.08.2014 / 20:52
3

I agree with Marcelo Diniz's answer however I want to say that the answer may be a bit more complete.

In order to make the solution more robust than checking HTTP_X_REQUESTED_WITH , you must also check the HTTP_REFERER so that the request source can be verified.

example:

if($_SERVER['HTTP_REFERER'] != $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"])
{
    header ("Location: index.php");<br>
}

It should be noted that both situations can have specific content because if someone with malicious intent so understand, these two variables can be easily distorted. However, it is always to be applied since most of the cases are ignored.

When the solution requires something more professional, then I advise you to work with Sessions and one of the variables will contain a different TOKEN with each call, in this way the system has become internal and almost impossible to falsify ... even with SessionHijacking .

    
26.08.2014 / 18:21