带有多个变量的PHP header_redirect


PHP header_redirect with multiple variables

我正在编写一个PHP脚本,该脚本将基于以下链接进行重定向:

header_redirect($_GET['redirect']);

URL为:

https://www.url.com/index.php?change_language=english&redirect=other_page.php?category=1234&limit=24

正如你所看到的,实际的页面是

https://www.url.com/index.php?change_language=english

然后重定向到另一个具有多个变量的页面,如:

&redirect=other_page.php?category=1234&limit=24

然而,当我运行上面的链接时,我只会被重定向到"other_page.php",并且其他变量会丢失。

我将如何实现这一点?

你可以使用一些加密和解密技巧来解决这个问题,我已经使用了base64_encodebase64_decode()函数来解决你的问题。

第1步:在您的html页面中

<?php $redirectUrl = base64_encode('other_page.php?category=1234&limit=24'); ?>
<a href="index.php?change_language=english&redirect=<?php echo $redirectUrl;?>">Link1 </a>

步骤2:header_redirect()函数中,您可以使用base64_decode()函数解码重定向刺痛并获得预期的刺痛。

function header_redirect($redirect){
      $redirect = base64_decode($redirect); // you can get the expected redirected url with query string
     //your redirect script
}

取决于您要做什么。

选项1:使用http_build_query。

尝试:

$target=$_GET['redirect'];
unset($_GET['redirect']);
$query_str=http_build_query($_GET);
header_redirect($target.'?'.$query_str);

如果您的起始URL是:

https://www.url.com/index.php?change_language=english&redirect=other_page.php&category=1234&limit=24

然后您将被重定向到:

https://www.url.com/other_page.php?change_language=english&category=1234&limit=24

选项2:使用rawurlencode和rawurldecode。

但是,如果您的目标是重定向到$_GET['redirect']中存储的任何内容(并忽略URL中的任何其他变量),那么在将other_page.php&category=1234&limit=24位放入起始URL之前,您需要对其进行编码。这将有效地转义特殊字符,并允许您简单地调用header_redirect(rawurldecode($_GET['redirect']));

假设您的起始URL是:

https://www.url.com/index.php?change_language=english&redirect=other_page.php%3Fcategory%3D1234%26limit%3D24

然后您将被重定向到:

https://www.url.com/other_page.php?category=1234&limit=24