Search code examples
phptouchstat

why stat() does not show correct value of mtime?


I have created simple testing function with a loop. It has a lot of echos because I want to know what exactly happens. Notice, there is a die command on the end of the loop, so it is not real loop. I call the function with test("523",$p);. This creates variable $fname = "523.txt" and $p may be set to 1; I found out that when I touch the file and set it some mtime, atime, values like 10, 1... the stat() does not return proper value. But if I remove the function (just the inner code stayes) so the stat() will return correct values 10 1; ... Any ideas what may went wrong in my function?

function test($n, $p){
  $fname = "$n.txt";
  echo "<h4>$n at ".time()."</h4>";
  for ($i = 0; $i<50; $i++ ){
    $start = microtime(true);

    $st = stat("$fname");
    echo "; 1) previous access by ".$st['mtime']." ".$st['atime']."; ";

    $fsize = filesize($fname);
    if ($fsize === 0)
     echo "! The fsize is 0; ";    
    else
      {
      $fp = fopen($fname, "r");
      $locked = flock($fp, LOCK_SH);
       $s = fread($fp, $fsize );
       $success = flock($fp, LOCK_UN);
       if ( $success === false  )
         die("; r flock release failed; ");
       $success = fclose($fp);
       if ( $success === false  )
         die("; fclose failed; ");
       // 10 - data načtená , $p - prohlížeč
       if ( $success )
         { 
         $result = touch("$fname",10,$p);
         echo "; TOUCH: $result;";
         }
       if ( strlen($s)<60 ) 
          echo "*$s LENGTH:".strlen($s)."<br>";
      }
    $st = stat("$fname");
    echo "; 2) previous access by ".$st['mtime']." ".$st['atime']."; ";
die;
  }
}

See the lines:

$result = touch("$fname",10,$p);

and

$st = stat("$fname");

Result ; 1) previous access by 1570715111 1570715111; ; TOUCH: 1;; 2) previous access by 1570715111 1570715111;


Solution

  • Quote from here: https://www.php.net/manual/en/function.stat.php

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

    Just add clearstatcache(); before calling stat for the second time