开发者

Keeping URL parameters during PHP redirect

开发者 https://www.devze.com 2023-04-04 05:43 出处:网络
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 HTM开发者_StackOverflow中文版L might b

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 HTM开发者_StackOverflow中文版L might be trying to interpret the &var as a character. 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


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:

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.
On the other hand, make sure that nothing is outputed to the browser BEFORE THE REDIRECT EXECUTES.


Redirecting index.php to hompage. same can be used for any other page redirection.

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

精彩评论

暂无评论...
验证码 换一张
取 消