1

Say I'm on /page_1.php. I run the following code under a certain condition:

global $URL_BEFORE_PAGE2;
$URL_BEFORE_PAGE2 = $_SERVER['REQUEST_URI'];
header('location: /page_2.php');

I am now on /page_2.php. This page contains the following link:

<a href="<?=$URL_BEFORE_PAGE2?>">Return to Previous Page</a>

PROBLEM: The link using $URL_BEFORE_PAGE2 points to /page_2.php instead of the expected /page_1.php.

I assume the problem is that $URL_BEFORE_PAGE2 is storing a reference to $_SERVER['REQUEST_URI'] instead of just storing the value. How can I keep the original value of $URL_BEFORE_PAGE2 without it updating every time $_SERVER['REQUEST_URI'] changes?

2 Answers2

1

On page_1.php, use the following code to create a session that will store the uri

session_start();

$_SESSION['URL_BEFORE_PAGE2'] = $_SERVER['REQUEST_URI'];
header('location: /index2.php');

On page_2.php, simply use the session to get the uri again

<?php
    session_start();
?>
<a href="<?=$_SESSION['URL_BEFORE_PAGE2']?>">Return to Previous Page</a>

More info on sessions

session_start()

No Name
  • 612
  • 6
  • 15
0

You could do that with javascript:

function goBack() {
    window.history.back();
}
<button onclick="goBack()">Go Back</button>

You could do that with PHP like this:

<?php
  header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
Ezequiel Fernandez
  • 954
  • 11
  • 18