user1227914
user1227914

Reputation: 3524

PHP header_redirect with multiple variables

I am writing a PHP script that will redirect based on a link like this:

header_redirect($_GET['redirect']);

And the URL being:

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

As you can see, the actual page is

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

and the redirect is then to another page with multiple variables like:

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

However, when I run the link above, I only get redirected to "other_page.php" and the additional variables are lost.

How would I achieve this?

Upvotes: 1

Views: 1895

Answers (2)

CragMonkey
CragMonkey

Reputation: 848

Depends on what you're trying to do.

Option 1: Use http_build_query.

Try:

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

If your starting URL is this:

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

You would then be redirected to:

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

Option 2: Use rawurlencode and rawurldecode.

However, if your goal is to be redirected to whatever you have stored in $_GET['redirect'] (and ignore any other variables in the URL), then you would need to encode the other_page.php&category=1234&limit=24 bit before you put it into your starting URL. This will effectively escape the special characters and allow you to simply call header_redirect(rawurldecode($_GET['redirect']));.

Say your starting URL is then:

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

You would then be redirected to:

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

Upvotes: 0

Krish R
Krish R

Reputation: 22741

You can solve this problem using some encryption and decryption trick, I have used base64_encode and base64_decode() function to solve your problem.

Step1: in your html page

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

Step 2: in your header_redirect() function, you can use base64_decode() function decode the redirect stings and get the expected one.

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

Upvotes: 1

Related Questions