简体   繁体   English

在PHP重定向期间保留URL参数

[英]Keeping URL parameters during PHP redirect

This isn't working: 这不起作用:

<?php
header('Location: www.mysite.com/index.php?foo=bar&var=abc');
?>

I end up with www.mysite.com/index.php?foo=bar I think HTML might be trying to interpret the &var as a character. 我最终得到了www.mysite.com/index.php?foo=bar我认为HTML可能会试图将&var解释为一个字符。 The initial variable is passed (after ?) but all subsequent are not (after &). 传递初始变量(在?之后),但后面的所有变量都不是(在&之后)。

if( isset($_SERVER['HTTPS'] ) ) {
  header('Location: https://'.$_SERVER['SERVER_NAME'].'/index.php?'.$_SERVER['QUERY_STRING']);
}
else{
  header('Location: http://'.$_SERVER['SERVER_NAME'].'/index.php?'.$_SERVER['QUERY_STRING']);
} 

use htmlspecialchars to prevent html injection 使用htmlspecialchars来防止html注入

Redirecting index.php to hompage. 将index.php重定向到hompage。 same can be used for any other page redirection. 同样可以用于任何其他页面重定向。

$url = str_replace('/index.php', '/', $_SERVER['REQUEST_URI']);
header('Location: '. $url, true,302);
exit();

I was testing that case with this: 我正在测试这个案例:

<?php
    if (isset($_GET['foo']) ) { 
        echo '<pre>';
        print_r($_GET);
        echo '</pre>';
        exit(); 
    }
    $fp='http://server/header.php?foo=bar&var=abc';
    header("Location: ".$fp);
    exit();
    ?>

I call the address: http://server/header.php and the redirect works fine to ' http://server/header.php?foo=bar&var=abc ' and the _GET is complete: 我调用地址: http://server/header.php ,重定向工作正常,为' http://server/header.php?foo = bar&var = abc ', _ GET完成:

Array
(
    [foo] => bar
    [var] => abc
)

Notice: 注意:

  1. location with first letter as capital letter. 第一个字母为大写字母的位置。
  2. the colon and space after "Location" “位置”后的冒号和空间
  3. the full link 完整的链接
  4. the exit() call. exit()调用。
On the other hand, make sure that nothing is outputed to the browser BEFORE THE REDIRECT EXECUTES. 另一方面,确保在REDIRECT EXECUTES之前没有任何内容输出到浏览器。

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

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