【问题标题】:What is the fastest way to strip a single GET parameter from a URL in PHP?从 PHP 中的 URL 中去除单个 GET 参数的最快方法是什么?
【发布时间】:2023-04-07 10:36:01
【问题描述】:

例子:

用户调用:

http://www.example.com/?mysecret=hello&second=world&third=bar

如果“mysecret”正确,则设置 cookie 并将用户重定向到:

http://www.example.com/?second=world&third=bar

代码示例:

if(is_page(MY_LOCKED_PAGE)) {

if($_COOKIE["unlocked"]=="y") {
    // proceed
} else if(isset($_GET["mysecret"])) {
    setcookie('unlocked','y',time()+3600*24*180,'/',"",false,true);

    // strip mysecret from the URL

    // redirect to the original URL without the get parameter "mysecret", but keeping other get parameters

} else {
    // redirect 404
}
}

填写缺失的代码 - 剥离参数 mysecret 并重定向到相同 url 的最快方法是什么?

【问题讨论】:

  • header("Location: ./?second=world&third=bar"); ?
  • 使用unset($_GET["mysecret"]) 删除它。
  • Ofc。但让我们假设我不知道其他 get 参数是什么。问题是拆分和重新解析 url 的最快方法。
  • @alpha 也许我想复杂我会试试

标签: php get url-redirection


【解决方案1】:

只需简单地unset() 你的mysecret 并利用http_build_query()$_GET 超级全局生成新网址:

unset($_GET['mysecret']);
$url = http_build_query($_GET);
// redirect
header("Location: {$url}");

这是Example

【讨论】:

  • 基本正确,但是我发布了对我有用的完整答案(也许更短的解决方案是可能的)。
【解决方案2】:

对我有用的完整答案如下:

    unset($_GET['mysecret']);

    $build = http_build_query($_GET);

    $uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);

    $prot = "http://";

    if(isset($_SERVER['HTTPS'])) {
        if ($_SERVER['HTTPS'] == "on") {
            $prot = "https://";
        }
    }

    $url = $prot . $_SERVER['HTTP_HOST'] . $uri_parts[0] . "?" . $build;

    // redirect
    header("Location: {$url}"); die;

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多