PHP - $_SERVER['HTTP_REFERER'] - how to store once, not again when a form submission occurs

StackOverflow https://stackoverflow.com/questions/17615051

  •  02-06-2022
  •  | 
  •  

Question

In PHP, how would I go about storing the variable "backurl"? (retrieved as shown below at the bottom - when the following constraints need to apply)

  • The variable "backurl" is storing the last php script viewed.
  • On first execute the variable "backurl" is stored and works correctly
  • When a form is submitted through $_GET or $_POST within that script, the variable will update as the previous URL has changed. (I don't want this to happen)

i.e. FROM -> TO (actual outcome - desired outcome)
page1.php -> page2.php (link goes to page1.php - as intended)
page2.php -> page2.php?test=yes (link goes to page2.php - I want it to go back to page1.php)

If anyone has any suggestions of how to do this, thank you very much!

$backurl =  $_SERVER['HTTP_REFERER'];
Was it helpful?

Solution

you could use sessions

<?php

session_start();
if(!isset($_SESSION['backurl'])){
$_SESSION['backurl'] = $_SERVER['HTTP_REFERER'];
}
?>
$_SESSION['backurl']; //contains the back url;

and if you nee to unset the backurl:

unset($_SESSION['backurl']);

OTHER TIPS

Set the backurl in session and access it whenever & however you needed in page2.php

There are several ways to do this. One could be updating your backurl only if the script page is different, using session.

e.g. (untested):

session_start();

if( $_SEVER['SCRIPT_NAME'] != $_SESSION['lastpage'] ){
    $_SESSION['backurl'] = $_SERVER['REQUEST_URI'];
}

This way, you'll only update the backurl when you call a different php page, leaving it unchanged when you go to the same page with different parameters (based on your example).

Adapt the code to your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top