PHP Function visitorPreviousPage() to Get Visitors Previous Page Url
PHP Function visitorPreviousPage() to Get the URL of the Page Visitor Just Came from/Previous Page
Home
Short:
/* -------------------------------------------------------------- * function to get page person just came from/previous page url * ---------------------------------------------------------- */ function visitorPreviousPage(string $defaultPage) { # Static variable to store the previous page value within the same request static $previousPage = null; # Construct the full URL for the current page $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST']; $currentPage = $scheme . '://' . $host . $_SERVER['REQUEST_URI']; # On the first call, initialize $previousPage based on the priority order if ($previousPage === null) { # Priority 1: Fetch from session if available if (isset($_SESSION['previous_page']) && !empty($_SESSION['previous_page'])) { $previousPage = $_SESSION['previous_page']; } # Priority 2: Fetch from HTTP_REFERER if available and valid elseif (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false) { $previousPage = $_SERVER['HTTP_REFERER']; } # Priority 3: Use default page else { $previousPage = $defaultPage; } # Update the session with the current page URL $_SESSION['previous_page'] = $currentPage; } else { # Update the session with the current page URL $_SESSION['previous_page'] = $currentPage; } return $previousPage; }
source code home