Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I would like to get the ID (or permalink) of the page the visitor visited just before visiting the current page - in other words the ID of the last page in the browser history.

Can this be done? Any idea how to do it?

share|improve this question
    
Search inside the print_r( $GLOBALS ); array. Not sure right now, but it maybe inside $_GET/_REQUEST/_SESSION/_SERVER;... –  kaiser Dec 7 '11 at 16:42
    
@kaiser cheers, there is indeed a HTTP_REFERER in _SERVER - giving me the URL of the previous page. Perfect! –  ptriek Dec 7 '11 at 16:50

1 Answer 1

up vote 2 down vote accepted

Break this down into two parts:

First, we create a variable that stores that last-visited page URL, like this:

$prev_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

Then, you could either use substr and strpos to trim down everything between ?= and the / after the ID number. like this:

$prev_url = 'http://www.yoursite.com/?p=123';
$id_block = substr($prev_url, strpos($prev_url, "?p=")+1);
$id = substr($id_block, 0, strpos($id_block, "/"));

.. Or, you could use jQuery/Javascript to achieve the same.

I haven't tested this but it should work - let me know how it does! Good luck ;)

share|improve this answer
    
thanks - i was already thinking in this direction, but php manual sais about this: "The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted." So I'm a bit in doubt whether it's the best way to go... –  ptriek Dec 7 '11 at 16:56
    
True - the HTTP_REFERER depends on the server alone. To be honest, I am unaware of any other solutions for this. If this is not a crucial function, I would go ahead and use HTTP_REFERER as it is pretty stable from agent to agent. –  cr0z3r Dec 7 '11 at 17:19
    
It's not a crucial function, so I'll just go with this & provide a fallback scenario.. Thanks for your help! –  ptriek Dec 7 '11 at 17:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.