PHP,如何检查第三方网站是否快速响应,与之交互


PHP, how to check if third-party website responds fast, to interact with it?

为了保护用户可以在类似论坛的页面上提交反馈的字段,我使用stopforumspam.com的API将访问者的IP与stopforum垃圾邮件黑名单进行比较。

然而,有时,stopforumspam会关闭,以进行维护,因为垃圾邮件发送者正在对域进行DDOS操作。这使得加载该页面几乎需要很长时间。

我当前的代码使用

try { } 
catch(Exception $e) { }

方法。

详细信息:

$visitorip=getip();
try
{
        // using code from http://guildwarsholland.nl/phphulp/testspambot.php to try and block spammers
        $xml_string = file_get_contents('http://www.stopforumspam.com/api?ip='.$visitorip);
                $xml = new SimpleXMLElement($xml_string);
                if($xml->appears == 'yes'){
                    $spambot = true;
                    file_put_contents("list.txt" , date('c').", ".$visitorip."'n", FILE_APPEND);
                    $spambot_info = $ip.',';
                    die("I'm sorry but there has been an error with the page, please try again tomorrow or contact the admin if your report can't wait, thank you!");
                } 
}
catch(Exception $e) 
{
        echo 'Error connecting to the main antispam checking database, please send an email to the admin through the main contact page, if that problem lasts for more than a pair of hours, THANK YOU !! <br>Here is the complete error message to report : <br>' .$e->getMessage();       
}

这是不完美的:当stopforumspam关闭时,在catch()错误消息出现并最终加载我的页面之前,将有整整45秒的时间加载空白页面。服务器等待时间,最大php执行时间,或标准等待延迟,最有可能。

你知道我如何将脚本尝试连接的时间(在抛出错误之前)缩短到最多10秒吗?非常感谢!

您有一些不同的选项。你的问题的答案是:

提出一个请求,然后等待它需要多长时间。

但你已经在这么做了,而且没有任何帮助。我想你真正想知道的是:

我如何避免让我的用户在我与可能较慢的第三方交互时等待

为您的请求设置超时

您需要在连接上设置一个超时。我建议使用curlCURLOPT_CONNECTTIMEOUT

$ch = curl_init();
$url = 'http://example.com/';
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
// Now you can work with $result

请注意,您可能需要使用curl-errno 检查错误

有关更多信息,请参阅curl手册和此问题。

缓存结果

我不知道stopforumspam的更新频率,但您可以很容易地将其页面写入本地文件,并在需要时进行检查。然后,您只需要读取一个本地文件,该文件将比。为了更新缓存版本,您可以设置计划任务(cron),也可以根据请求检查缓存文件的修改时间。

将两者结合

你最好的选择可能是这两种技术的结合。