Check if file exists at run time [closed]

-2

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

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

How can I do this?

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>";
    
asked by anonymous 24.09.2018 / 23:00

2 answers

2

First, your code is redundant. For:

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

It's the same as:

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

If the test is false, the execution exits the loop. And you're using continue wrong, continue say to the interpreter "This cycle has already gone, you can go to the next one" by ignoring the rest of the tag inside the loop of this iteration and moving on to the next one. That is, its continue would make more sense being a break because if the condition of if is true the execution leaves the loop. But if the condition of if is equal to the condition of while , then it does not make sense to have 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 is not working:

I think it might look like this:

PHP's is_file function makes use of caching to decrease I / O for performance reasons. According to documentation:

  

Note: The results of this function are cached. 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 it in conjunction with the 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>";
    
24.09.2018 / 23:26
0

You can use file_exists:

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

$teste = file_exists($filename)

And exit the function using break

if (!$teste) {
    break;
}

Follow links for study:

break

file_exists

    
24.09.2018 / 23:13