7

Erm... what the title says really; I have a PHP script executed by an AJAX call on page1. Can I access page1's current URL/URI from inside the PHP called by AJAX using standard $_GET, or do I need to pass the parameter I want along with the rest of the data to the AJAX page?

Thanks,

James

Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • 1
    Here's [a related question](http://stackoverflow.com/questions/165975/determining-referer-in-php). – Lee Dec 19 '10 at 22:04

1 Answers1

17

Referrer should do the trick

echo $_SERVER['HTTP_REFERER']

from within your php script

Just to get more specific: Page1 makes a call to Page2. You'd then output the variable above to find the url of page1. If you need the url of page2, then you would use:

$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

You should check if these exist before trying to access them. I sometimes do this:

$server = array_merge(array('HTTP_HOST'=>null, 'REQUEST_URI'=>null, 'HTTP_REFERER'=>null), $_SERVER);

I would then access the variable "$server" instead of $_SERVER. Alternatively, you could use @$_SERVER[] too which will generally supress errors.

Jason
  • 15,064
  • 15
  • 65
  • 105
  • 1
    As I understand it, some browsers don't send Referrer along with an AJAX request (as far as the HTTP spec is concerned, it's an optional header, so it may or may not be there in any case). At any rate, I'd be sure to check this on all supported versions of all supported browsers before I settled on code that depends on it. – Lee Dec 19 '10 at 22:07
  • Thanks Lee - I'll bear that in mind and send the URL parameters I want along with the AJAX request. – Bojangles Dec 19 '10 at 22:09
  • Okay so doing some further reading, it's true the referrer isn't always there, but i can't find a page that shows me which browsers would send it or not. If that is the case, then you could either pass the uri string on through your script, or if you want an (arguably) cleaner way, then perhaps you could set the referer through sessions. eg $_SESSION['ref'] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; Make sure you copy the value out (if it exists) before you overwrite it. – Jason Dec 19 '10 at 22:12
  • Note - you should not rely on this for security as this can be easily spoofed. Instead, if you want to do this for security there are other methods you can employ. – chaimp Dec 19 '10 at 22:20
  • Thank you all for your comments. I have decided to just send the data I want along with the other stuff, not use `REQUEST_URI`, due to security concerns. It's not a massively important piece of data - just a forum ID. – Bojangles Dec 19 '10 at 23:20
  • echo $_SERVER['HTTP_REFERER'] is helpful. – Jitesh Sojitra Jun 14 '16 at 19:26