PHP Redirect with query parameters

Issue

Let’s say I have the following URL:

http://example.com/index.php?user/1234

What I want the PHP query to do is redirect the user to the following URL:

http://example.com/test/index.php?user/1234

Of course, the URL should not only redirect ?user/1234 but also ?anything/343. I want to leave the url intact and only add the /test/ to it, and leave the part afterwards the same.

How do I accomplish that? All I could find is just general redirection and not specific to URLs. Thanks.

Solution

I modified Kasia Gogolek’s answer so that it works for me. This is the solution to my question:

$fullUrl = $_SERVER[REQUEST_URI];
// split the url
$url = parse_url($fullUrl);
$url['path'] = "/test" . $url['path'];
// create the new url with test in the path
$newUrl = $url['path']."?".$url['query'];
header("Location:" .$newUrl);

Answered By – OldMcDonald

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published