PHP - Wait for file to exist

10,435

Solution 1

this should works fine

set_time_limit(0);

echo "Script began: " . date("d-m-Y h:i:s") . "<br>";

do {
    if (file_exists("test.txt")) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
} while(true);

Solution 2

I trust that you have other safeguards in place to make sure that you’re not in an infinite loop.

while(!file_exists('test.txt'));
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";

would be simpler.

Anyway, your problem is with your pretest. Since it fails to begin with, it never repeats. What you need is a post test:

do {
    if (file_exists("test.txt")) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
} while(!file_exists("test.txt"));

Solution 3

I suppose you should use this approach:

set_time_limit(0);

echo "Script began: " . date("d-m-Y h:i:s") . "<br>";

while (true) {
    // we will always check for file existence at least one time
    // so if `test.txt` already exists - you will see the message
    // if not - script will wait until file appears in a folder
    if (file_exists("test.txt")) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
}

Solution 4

Brief experiments suggest that waiting for an asynchronous file system change (using PHP as a module in Apache) must yield control in the loop. Otherwise, the number of loops spent waiting (such as for a file to be deleted by unlink()) seems to be random over a very large range. Yielding inside such a loop can be done by "usleep(250000)", which will yield control for 1/4 of a second.

Share:
10,435
zeddex
Author by

zeddex

Is a game and web developer

Updated on June 30, 2022

Comments

  • zeddex
    zeddex almost 2 years

    I wanted to exec a exe which generates txt files and also in another script then check that the txt files have been created.

    In xampp i am simply dragging in a test.txt file to the following php scripts dir but it doesn't seem to work correctly, also if i add in text.txt to the dir and start the script rather than starting before it is added then the second echo never seems to happen.

    How can i make PHP Wait for the text file to exist and then continue?

    set_time_limit(0);
    
    echo "Script began: " . date("d-m-Y h:i:s") . "<br>";
    
    $status = file_exists("test.txt");
    while($status != true) {
        if ($status == true) {
            echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
            break;
        }
    }
    

    This also does not work:

    set_time_limit(0);
    
    echo "Script began: " . date("d-m-Y h:i:s") . "<br>";
    
    while(!file_exists("test.txt")) {
        if (file_exists("test.txt")) {
            echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
            break;
        }
    }