PHP检测url是否重定向并重试重定向

时间:2013-02-27 08:56:49

标签: php curl http-headers http-redirect

我希望在我的服务器上完成处理后将用户重定向到远程服务器。有时,由于用户端的网络连接超时,重定向不会发生,导致他/她的页面无法获得更新状态。

我目前使用的是

header('Location: http://anotherwebsite.com');

如果失败,它将不会再试一次......我怎样才能实现'将再试一次'

$retry_limit = 0;
while(//http status code not 301 or 302 && $retry_limit < 3)
{
    header('Location: http://anotherwebsite.com');

    $retry_limit++;
}

如果我使用cURL,我会感到困惑,如果我也实现了标题,它会加倍重定向......或者我误解了它?

非常感谢!

2 个答案:

答案 0 :(得分:1)

正如已经指出的那样,header()只会触发HTTP标头并忘记,因此使用PHP,您将无法轻松实现重试机制。

但是你要解决的根本问题是什么?如果您重定向到的合作伙伴网站过载,有时只会对第二次或第三次尝试做出反应:严重的话,您应该让该服务器更可靠地工作。

另一方面,如果您只是想找到一种方法来注意到其他服务器可能的停机时间并相应地通知您的用户,您可以添加一个快速的服务器到服务器检查你的代码。如果其他服务器已关闭,您可以重定向到其他页面并道歉或提供重试链接。

查看this answer有关ping服务器的方法,以确定它是否已启动。

粗略的解决方案可能如下所示:

<?php
$url = 'http://anotherwebsite.com';

if(pingDomain($url) != -1) {
    header('Location: ' . $url);
} else {
    header('Location: sorry_retry_later.html');
}

// Ping function, see
// https://tournasdimitrios1.wordpress.com/2010/10/15/check-your-server-status-a-basic-ping-with-php/
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

答案 1 :(得分:0)

header只能用于一次性重定向。由于没有返回值,您无法以这种方式进行检查。您应首先尝试使用 JSON 来检查网站是否有响应,如果是,请重定向用户,否则请写入错误消息或其他内容。

Reference for JSON

我个人没有使用过这个,但看到其他人用这种方法成功地做到了。

相关问题