Check if file exists at runtime

Asked

Viewed 52 times

-2

I need to check if a file has been deleted while running a particular function.

At the start of implementation the result of is_file is true, but during execution the file will be deleted and, this is the condition to follow with code: the file no longer exists.

How can I do?

Below the code:

<?php

$raiz = dirname(__FILE__);
$teste = is_file($raiz.'/teste.pid');

while($teste == true){
    $teste = is_file($raiz . '/teste.pid');
    if ($teste == false) {
        continue;
    }
}
echo " --- continua execução --- <br>";
  • 2

    You know what the continue ago?

2 answers

2

First, your code is redundant. Yeah:

while ($teste == true) {
    $teste = is_file($raiz . '/teste.pid');
    if ($teste == false) {
        continue;
    }
}

Is the same as:

while ($teste == true) {
    $teste = is_file($raiz . '/teste.pid');
}

Because if the test is false the execution comes out of the loop. And you are using the continue wrong, the continue tells the interpreter "That cycle is gone, you can go to the next one" ignoring the rest of the code within the loop from this iteration and moving on to the next. That is, your continue it would make more sense to be a break because if the if condition is true the execution leaves the loop. However if the if is equal to the condition of while, then it makes no sense the existence of this if.

That said, your while could still be just:

while (is_file($raiz . '/teste.pid'));

But let’s go to what I believe is the reason your code isn’t working:

I think they may be as follows:

The function is_file PHP makes use of cache to decrease I/O operations for performance reasons. According to documentation:

Note: The results of this function are curled. See clearstatcache() for more details.

So to solve this you would have to invalidate the cache and try again. Maybe it is not the best solution, after all this cache exists for a reason, but I would use in conjunction with the function sleep() to pause the script and wait for the file to be deleted.

An example:

<?php
$raiz = dirname(__FILE__);

while (is_file($raiz . '/teste.pid')) {
    sleep(1);
    clearstatcache();
}

echo " --- continua execução --- <br>";

0

You can use file_exists:

$filename = '/caminho/para/arquivo.txt';

$teste = file_exists($filename)

And exit function using break

if (!$teste) {
    break;
}

Below are links to study:

break

file_exists

Browser other questions tagged

You are not signed in. Login or sign up in order to post.