Search code examples
phpjquerydialoghttp-referer

PHP: How to detect direct requests of external visitors?


I would like to detect/prevent/forward direct requests of external visitors. Some scripts should only be displayed in a jQuery dialog.

My current code:

<script>
$(".dialog").click(function() {
    // some code for validation
    // ...
    $("#dialog").load(this.href).dialog();
});
</script>    

<a href="http://domain.de/path/to/form/" class="dialog">Open me in a dialog</a>

That works fine BUT if I open this link in a new tab/window (e.g. by clicking the middle mouse-button), the form will be displayed "naked".

In this case I would like to forward the user to the refered page, e.g.:

if ($requester != $server) {
    header ("Location: " . $_SERVER["HTTP_REFERER"];
}

How can I detect $requester and $server? I don't want to block every script or a whole directory!

Thanks in advance!


Solution

  • To add to what @Dharman suggested jQuery adds a header to all its ajax request called HTTP_X_REQUESTED_WITH so you could simply check against this header in the $_SERVER global array.

    Example:

    if($_SERVER['HTTP_REFERER']!=$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"])
    {
        // check if the request is ajax 
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
              $_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest' ){
              // ajax content loading
        }
    
        header ("Location: index.php");
    }