简体   繁体   English

如何在PHP变量中存储当前URL并中断对$ _SERVER ['REQUEST_URI']的引用?

[英]How to store current URL in a PHP variable and break the reference to $_SERVER['REQUEST_URI']?

Say I'm on /page_1.php . 说我在/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 . 我现在在/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 . 问题:使用$ URL_BEFORE_PAGE2的链接指向/page_2.php而不是预期的/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. 我认为问题是$ URL_BEFORE_PAGE2正在存储对$ _SERVER ['REQUEST_URI']的引用,而不是仅仅存储值。 How can I keep the original value of $URL_BEFORE_PAGE2 without it updating every time $_SERVER['REQUEST_URI'] changes? 如何在$ _SERVER ['REQUEST_URI']每次更改时不更新$ URL_BEFORE_PAGE2的原始值?

On page_1.php, use the following code to create a session that will store the uri 在page_1.php上,使用以下代码创建一个会话,该会话将存储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 在page_2.php上,只需使用会话即可再次获取uri

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

More info on sessions 有关会话的更多信息

session_start() 在session_start()

You could do that with javascript: 您可以使用javascript来做到这一点:

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

You could do that with PHP like this: 您可以使用PHP来做到这一点,例如:

 <?php header('Location: ' . $_SERVER['HTTP_REFERER']); ?> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM