GSto
GSto

Reputation: 42350

PHP: 301 Redirect Page while maintaining GET variables

I have a page that has been replaced with a new page of a different name, is there a way to redirect this page while maintaining _GET variables passed in the url.

what I have right now:

old-page.php

header('Location: http://www.example.com/new-page.php', true, '301');

when users navigate to a url like old-page.php?var=1 they are taken to new-page.php , how can I get it to redirect them to new-page.php?var=1? the query string can be several different things, so I'd like a solution that can work w/ any combination of get variables.

Upvotes: 1

Views: 2135

Answers (4)

Shi
Shi

Reputation: 4258

If you are using Apache, you can use the almighty mod_rewrite. This way, you can rewrite everything - GET, POST and more.

If you want to do it in PHP, in order to make it right(tm), you need to consider $_SERVER['HTTPS'], $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_PORT'] as well. Just because when running HTTPS on a custom port, you maybe do not want to redirect to HTTP using default port.

Upvotes: 0

Marty
Marty

Reputation: 39456

Can you do something like:

$parse = '';

foreach($_GET as $i => $j)
    $parse .= "$i=$j&";

$parse = (strlen($parse) > 0 ? "?" : "") . substr($parse, 0, -1);

header("Location: old-page.php$parse");

Upvotes: 0

Wrikken
Wrikken

Reputation: 70470

header('Location: http://www.example.com/new-page.php'
   .(!empty($_SERVER['QUERY_STRING'])?'?'.$_SERVER['QUERY_STRING']:''),
   true, '301');

Upvotes: 4

Ibu
Ibu

Reputation: 43810

You can either use sessions:

session_start();
$_SESSION['your var'] = "value";

or you can pass it in your redirect url

header('Location: http://www.example.com/new-page.php?key=value', true, '301');

Upvotes: 0

Related Questions