开发者

How can I run a "background" infant loop with PHP?

I am looking for a 开发者_如何学运维way to check if there are any new files in a directory. Can I do this live with some infant loop? When I say:

   <?php
        while (true) {
            $files = glob("../example/*.txt");
          $count_posts = $files !== false ? count($files) : 0;
            if ($count_posts > 0) {
                break;
            print("WE DID IT!!!!!!!");
            }
        }
        ?> 

Three weird things happen: 1.) The page will keep loading - which I can't have 2.) It won't print "WE DID IT!!!!!!!!!" and 3.) No content will be shown until there is a new file. How can I do this?


As far as looping through a directory to check for files use the DirectoryIterator, or if there are sub-folders the RecursiveDirectoryIterator. Your while loop will be caught in an infinite loop if the glob statement returns false or 0.

For example:

$iterator = new DirectoryIterator('../example');
foreach ($iterator as $path) {
  if ($path->isFile()) {
     if (strpos($path->getFilename(), '.txt') !== false) {
         print("WE DID IT!!!!!!!");
         break;
     }
}

Or with a recursive directory iterator..

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('../example'));
foreach ($iterator as $path) {
   ...
}

If you need to run this as a background task you need to use AJAX, as Ben suggests. A normal PHP request via a web page is designed to load everything and display the contents back to the page. AJAX requests are the only way to do asynchronous requests on the web. See http://api.jquery.com/jQuery.ajax/


The simple answer is that you can't do it without using sockets and/or Javascript. PHP won't return any information until the entire page is completely loaded, in this instance nothing will display until the break clause is called.

I'd have a seperate script that checks for new files in the folder that's polled by javascript via setTimeout and AJAX every X seconds.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜