Prevent Users From Opening a Page Directly?

Discussion in 'PHP' started by conorod, May 16, 2013.

  1. #1
    I have a page on my site which I want to be able to request using AJAX/Microsoft.XMLHTTP from another page on the site, but I don't want users to be able to open the page directly by typing the URL into their browser. Is there an easy way to do this using PHP?
     
    conorod, May 16, 2013 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    You can stop the average person from going to this URL directly, but if someone really wants to, he'll get there somehow.

    In your AJAX response script, one thing you could do is this:
    
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) OR strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
    {
        exit();
    }
    
    PHP:
    EDIT: Make sure you don't cache the response. Otherwise, the user might be able to go to the URL once he requested the page via your AJAX script.
     
    nico_swd, May 16, 2013 IP
  3. Marcel Preda

    Marcel Preda Member

    Messages:
    21
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    43
    #3
    I think that you can use $_SERVER['HTTP_REFERER'] , it means the page from which request have been done. In your case $_SERVER['HTTP_REFERER'] have to be an URL of your domain. Probable in combination with $_SERVER['HTTP_X_REQUESTED_WITH'] it will be super safe.

    BR,
    Marcel
     
    Marcel Preda, Jun 4, 2013 IP
  4. dragos_tt

    dragos_tt Greenhorn

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #4
    I would make that AJAX call using the POST method. Faking a POST request is harder than a GET one. So if the request is not a POST, just die() your script execution.
     
    dragos_tt, Jun 5, 2013 IP