【问题标题】:PHP - set time limit effectivelyPHP - 有效地设置时间限制
【发布时间】:2012-05-08 21:04:47
【问题描述】:

我有一个简单的脚本,如果它发现用户正在手机上浏览,它会重定向到网站的移动版本。它使用 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
}
?>

还有here is source of TeraWurflRemoteClient.php 包含在内。它具有documentation 中提到的可选超时参数:

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

【问题讨论】:

    标签: php performance time


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我刚找到它。如何在我的脚本中使用它,以便在超时的情况下重定向到桌面网站?
    • 你已经写对了。尝试使用 catch(Exception) 块。在此处添加 header('位置:website.pl/');并退出;尝试{..getCapabilitiesFromAgent(... } catch(Exception $ex) {.. 重定向到默认站点...}
    • 我终于做到了,不能在这里使用 header() (因为在异常情况下已经有来自 TeraWurflRemoteClient.php 的输出)。我用 printf("
    • 似乎在 php.ini 中打开了 display_errors 选项。你可以在那里改变它。在生产站点中显示 php 错误是不好的。它仅在开发人员机器中有用。如果您无法访问 php.ini,请尝试编写 ini_set('display_errors', 0); php 脚本开头的某处。
    【解决方案2】:

    尝试通过在其类中对 TeraWurfl 的 HTTP 请求设置一个非常短的超时来实现这一点,这样如果响应在 2-3 秒内没有返回,则认为该检查为假并显示完整的网站.

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

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

    此外,我在研究 this 时发现了它,你可能想读一读,但我会说除非你非常清楚事情是如何工作的,否则不要分叉。

    刚才 Adelf 发布了 TeraWurflRemoteClient 类的默认超时时间为 1 秒,这样可以解决您的问题,但无论如何我都会发布我的答案。

    【讨论】:

    • 谢谢。对于我在这个主题上非常糟糕的技能来说,这有点太多了。现在我只需要找到如何使用 TeraWurlf 超时来达到我的目的。
    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多