Redirect with PHP and skip specific parameter

Posted by

Since I’ve started using friendly URLS in my website, I’m redirecting every page to the new version, only if the registered user has a “username” in his profile.

So, I’m redirecting from:

https://tribbr.me/post.php?id=850

with:

header("Location:/".$if_username."/post/".$post_id."?".$_SERVER['QUERY_STRING']); exit();

To keep all GET parameters…. but the problem is that this header request, obviously with $_SERVER['QUERY_STRING'] is adding the post id too to the URL, and when redirected, this is the final URL:

https://tribbr.me/TribeMasters/post/850?id=850

Is it possible to just skip the id=850 parameter to the URL redirection? Since it is a duplicated parameter: post/850 and id=850 are the same.

Thanks for helping me 🙂

Anwser 1

@DE_‘s answer is best. But If you are not familiar with Regex, This is an alternative way.

function removeGetParam($param){

 $params = $_GET;

 // removing the key
 unset($params[$param]); 

 // joining and returning the rest
 return implode(',', array_map(function ($value, $key) { 
            return $key.'='.$value;
          },$params, array_keys($params))
        );
}

$filtered_params = removeGetParam('id');
header("Location:/".$if_username."/post/".$post_id."?".$filtered_params);
  • Yes! Sometimes the post URL is https://tribbr.me/post.php?id=850&ref=51&fname=Guillermo&more..... So I need to redirect to: https://tribbr.me/username/post/850?ref=51&fnameGuillermo&more... – Guillermo Esquivel Obregon
  • Just remove ."?".$_SERVER['QUERY_STRING']? There’s no reason to pass that in if you don’t want it. Or do you have other query parameters you want to pass?

Answer 2

David Walsh did a good article on this redirect to another page in php with parameters

function remove_querystring_var($url, $key) { 
    $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); 
    $url = substr($url, 0, -1); 
    return $url; 
}

those are a group of characters captured in the brackets () according to their respective positions of php redirect with parameters

For me, worked better with @BadPiggie answer since I can’t figure out how do I specify id parameter in this function

More Post Like This :- How to Avoid Function Calling Repeatedly in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *