【问题标题】:Conditional redirect not working in else condition条件重定向在其他条件下不起作用
【发布时间】:2023-03-30 19:05:01
【问题描述】:

我们希望通过 PHP 将旧 URL 重定向到新位置。 (请不要谈论这是否是最好的方法;这是已经决定的。)

如果用户转到http://oldurl.com,我们希望重定向到http://newurl.com。如果他们转到http://oldurl.com/locations/illinois/12345(或任何其他这种格式的基于位置的网址),我们希望重定向到http://newurl.com/locations/illinois/12345

<?php
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);


if(is_array($segments) && in_array("locations", $segments)) {
    header('Location: http://newurl.com/locations/' . $segments[2] . '/' . $segments[3]);
}
else {
    header('Location: http://newurl.com');
}

if 条件有效 - 它重定向到动态构建的 url。但是当用户转到http://oldurl.com 时,它不会点击 else 条件并重定向到 http://newurl.com,而是停留在原始 url 上并提供一个空白页面。

知道为什么吗?

【问题讨论】:

  • 尝试查看错误日志。空白页通常意味着 500 错误,并且会在错误日志中写入一些内容。
  • 空白页可能意味着错误。 php.net/manual/en/function.error-reporting.php - 使用它并记录或显示,然后回来告诉我们它是什么,如果有错误。
  • var_dump($segments); 在您的页面上。看看你主页上的$_SERVER['REQUEST_URI'] 是否有任何内容。
  • 这是奇怪的部分 - 日志中没有错误。而且我已经完成了$segments的回声;它包含我期望它包含的内容。
  • 您是否尝试过在每个header 之后执行exit,否则它似乎对我有用。我猜代码在你显示的代码之后会继续做其他事情

标签: php redirect


【解决方案1】:

这行得通吗?

<?php
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$url = $_SERVER['REQUEST_URI_PATH'];
if (substr($url, 0, 7) == "http://")
$url = substr($url, 7, $url.length);

$segments = explode('/', $url, 2);

if(is_array($segments)) {
    header('Location: http://order.pizzahut.com/' . $segments[1]);
}
else {
    header('Location: http://order.pizzahut.com');
}

您可以在/ 之后的第一个斜杠/ 之后拆分 URL,而不是将 URL 拆分为多个字符串

【讨论】:

    【解决方案2】:

    is_array在这种情况下总是会返回true,因为一个路径,不管怎样,即使是根目录,也是以/开头的。这将导致字符串像这样拆分[0]/[1]

    如果你的REQUEST_URI 是/,你将得到一个数组,其中包含两个都等于"" 的条目

    这应该可行。

    <?php
        $_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
        if(!(count($segments) == 2) && !(in_array("", $segments))) {
            header('Location: http://order.pizzahut.com/locations/' . $segments[2] . '/' . $segments[3]);
        }
        else {
            header('Location: http://order.pizzahut.com');
        }
    

    如果我没有遗漏什么,这应该可以。

    【讨论】:

    • with 2 entries - 一个条目。 "".
    • is_array($segments) 可能总是在此代码中返回 true,但 in_array("locations", $segments) 不会。
    • @u_mulder 不,我已经在我的代码中对此进行了测试。它返回 2 个条目,因为对 document_root 的请求将返回 / 这导致数组返回两个结果,/ 之前和之后的空字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多