anon
anon

Reputation:

How to echo the last visited page in PHP?

I don't know is there is a PHP function like the ones that start with $_SERVER[''] That tell user which page he came from, on his current page.

ex. If I was browsing foo.com?id=abc then went to foo.com?id=efg, I need the current page to tell me that I came directly from foo.com?id=abc

I need this code badly, so any help is appreciated.

Upvotes: 0

Views: 5262

Answers (4)

Ken D
Ken D

Reputation: 5968

Yes, and this is not only in PHP, this is a part of the HTTP protocol specification, Use:

$_SERVER['HTTP_REFERRER']

Upvotes: 2

geekman
geekman

Reputation: 2244

The HTTP_REFERRER gives address of the page that requested the file. For example an image on a page is a separate request, and this request has a $_SERVER['HTTP_REFERRER'] set to the page.

I don't think browsers allow servers to access history. It can be done with JavaScript, though only a back button can be provided, the url cannot be accessed easily. Though it can be achieved using a simple css and javascript trick by accessing the computed color to a link.

Upvotes: 2

David
David

Reputation: 2065

The $_SERVER variables should not be relied upon to provide accurate answers. You should use PHP Sessions to track what page they come from, and simply update it everytime they go to a new page. Something along the lines of:

session_start();
if(!empty($_SESSION['visited_pages'])) {
  $_SESSION['visited_pages']['prev'] = $_SESSION['visited_pages']['current'];
}else {
  $_SESSION['visited_pages']['prev'] = 'No previous page';
}
$_SESSION['visited_pages']['current'] = $_SERVER['REQUEST_URI'];

Then to access the previous page, access the: $_SESSION['visited_pages']['prev']

Upvotes: 3

Marcin Orlowski
Marcin Orlowski

Reputation: 75619

It is $_SERVER['HTTP_REFERER']. But it is filled only if browser did so. Otherwise you need to track user yourself (i.e. by storing last page in session)

Upvotes: 4

Related Questions