PHP脚本中的无限循环返回错误


Endless Loop in PHP script returns Error

我想有一个推送连接到我的客户端。如果文件包含单词true,则应该通知它。这工作良好与以下脚本,但我总是得到一个错误后50秒。您将看到下面的错误:

如何修复这个错误?

<?php
    set_time_limit(3600);
    $content ="";
    while($content!="true"){
        sleep(1);
        $content = file_get_contents("test.txt");
    }
    echo "now";
?>

这里是浏览器在50秒后的结果。

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, sh@lorchs.de and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.

apache配置:

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 3600
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 0
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

在php.ini中搜索max_execution_time

增加php.ini中max_execution_time的值&在Apache上有一个max_input_time设置,它定义了无论大小如何,等待post数据的时间。如果这个时间过了,连接将关闭,甚至不需要访问php.

File get contents返回一个字符串中的所有内容。我认为你要做的是遍历行并搜索"true"是否在那行找到,找到true的位置然后返回在那之前的所有内容?

请不要让file_get_contents()返回整个文件的字符串。

只要$content不等于 string "true",

while-loop就会迭代。如果你的文件只返回内容"true",那么它将退出循环,否则不退出。

我猜你想做这样的事情:

<?php
    $content ="";
    while(!strstr($content,"true")) {
        sleep(1);
        $content = file_get_contents("test.txt");
    }
    echo "now";
?>

代码除了创建一个不必要的循环来检查文件中的字符串之外,实际上没有做任何事情。