PHP - 有效设置时间限制


PHP - set time limit effectively

我有一个简单的脚本,如果发现用户正在手机上浏览,它会重定向到网站的移动版本。它使用Tera-WURFL网络服务来实现这一目标,并将其放置在Tera-WURFL本身以外的其他主机上。我想保护它,以防 Tera-WURFL 托管停机。换句话说,如果我的脚本运行时间超过一秒,请停止执行它并重定向到常规网站。如何有效地做到这一点(这样CPU就不会被脚本负担过重)?

编辑:看起来TeraWurflRemoteClient类具有超时属性。请阅读下文。现在我需要找到如何将其包含在我的脚本中,以便在出现此超时时它会重定向到常规网站。

这是脚本:

// Instantiate a new TeraWurflRemoteClient object
$wurflObj = new TeraWurflRemoteClient('http://my-Tera-WURFL-install.pl/webservicep.php');
// Define which capabilities you want to test for. Full list: http://wurfl.sourceforge.net/help_doc.php#product_info
$capabilities = array("product_info");
// Define the response format (XML or JSON)
$data_format = TeraWurflRemoteClient::$FORMAT_JSON;
// Call the remote service (the first parameter is the User Agent - leave it as null to let TeraWurflRemoteClient find the user agent from the server global variable)
$wurflObj->getCapabilitiesFromAgent(null, $capabilities, $data_format);
// Use the results to serve the appropriate interface
if ($wurflObj->getDeviceCapability("is_tablet") || !$wurflObj->getDeviceCapability("is_wireless_device") || $_GET["ver"]=="desktop") {
    header('Location: http://website.pl/'); //default index file
} else {
header('Location: http://m.website.pl/'); //where to go
}
?>

这是TeraWurflRemoteClient的来源.php它被包括在内。它具有文档中提到的可选超时参数:

// The timeout in seconds to wait for the server to respond before giving up
$timeout = 1;

TeraWurflRemoteClient 类具有超时属性。正如我在文档中看到的那样,默认情况下是 1 秒。因此,此脚本的执行时间不会超过一秒。

尝试通过在类内对 TeraWurfl 的 HTTP 请求设置非常短的超时来实现此目的,这样如果响应在 2-3 秒内没有返回,请考虑检查是错误的并显示完整的网站。

查找设置

较短超时的位置可能会有所不同,具体取决于用于发出 HTTP 请求的传输。就像在 Curl 中一样,您可以设置 HTTP 请求的超时。

在此之后,请将您的 HTTP 请求超时重置回原来的值,这样您就不会影响任何其他代码。

我在研究它时也发现了这个,你可能想读一读,尽管我会说远离分叉,除非你非常了解事情是如何工作的。

刚才 Adelf 发布了 TeraWurflRemoteClient 类默认超时为 1 秒,因此可以解决您的问题,但我还是会发布我的答案。