Block PHP page to only display data if it is an AJAX request

Asked

Viewed 825 times

4

I have a file .php which 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 go normally on the page index.html and see the news that was uploaded via AJAX and PHP, but the user can also go to the page noticias.php and see all the news on the page. But I didn’t want this, there’s no way PHP can return data to AJAX or something? So that the user cannot directly access the noticias.php?

2 answers

6

What you can verify is in relation 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
}

3

I agree with the reply of Marcelo Diniz however I want to say that the answer can be a little more complete.

To make the solution more robust beyond the verification of the HTTP_X_REQUESTED_WITH the HTTP_REFERER the origin of the request.

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 malicious so wishes, these two variables can be easily distorted. However it is always to be applied because it misleads most cases.

When the solution requires something more professional, then I advise working with Sessions and one of the variables will contain a different TOKEN each call, so the system has become internal and almost impossible to falsify... even with Sessionhijacking.

  • Thanks Marcelo for the correction in formatting the code present in the reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.