【问题标题】:Redirect with PHP and skip specific parameter使用 PHP 重定向并跳过特定参数
【发布时间】:2020-09-16 00:37:14
【问题描述】:

自从我开始在我的网站中使用友好 URL,我将每个页面重定向到新版本,前提是注册用户的个人资料中有“用户名”。

所以,我的重定向来自:

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

与:

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

要保留所有 GET 参数....但问题是这个标头请求,显然带有 $_SERVER['QUERY_STRING'] 正在将帖子 ID 也添加到 URL,并且在重定向时,这是最终 URL:

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

是否可以跳过 id=850 参数到 URL 重定向?由于是重复参数:post/850id=850是一样的。

谢谢你帮助我:)

【问题讨论】:

  • 只删除."?".$_SERVER['QUERY_STRING']?如果您不想要它,就没有理由传递它。或者您还有其他要传递的查询参数吗?
  • 是的!有时帖子网址是https://tribbr.me/post.php?id=850&ref=51&fname=Guillermo&more..... 所以我需要重定向到:https://tribbr.me/username/post/850?ref=51&fnameGuillermo&more...

标签: php redirect http-headers


【解决方案1】:

大卫沃尔什在这方面写了一篇很好的文章

https://davidwalsh.name/php-remove-variable

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

【讨论】:

  • 感谢分享。那些$1$2$4 变量是什么?
  • @GuillermoEsquivelObregón 这些是括号()中根据各自位置捕获的一组字符
  • 感谢您帮助我 :) 对我来说,使用 @BadPiggie 答案效果更好,因为我不知道如何在此函数中指定 id 参数,但非常感谢 :)
【解决方案2】:

@DE_ 的回答是最好的。但是如果你不熟悉Regex,这是另一种方式。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 2017-04-29
    • 1970-01-01
    • 2020-05-21
    • 2010-10-09
    • 1970-01-01
    • 2014-12-28
    • 2018-07-17
    相关资源
    最近更新 更多