php - How to check if file handle still points to file -


is there way in php test if filehandle resource still points file in file system opened? e.g. in code:

<?php  $filename = './foo.txt'; $filehandle = fopen($filename, 'c');  $unlinked = unlink($filename);  if (!$unlinked) {     echo "failed unlink file.";     exit(0); }  file_put_contents($filename, "blah blah");  // file $filename exist here, want check // $filehandle still points file on filesystem name $filename. ?> 

at end of code, filehandle still exists no longer references file './foo.txt' on filesystem. instead still holds reference original file has been unlinked, i.e. has no active entry in filesystem, , writing data filehandle not affect contents of file called $filename.

is there (preferably atomic) operation determine $filehandle 'invalid' in sense no longer points original file?

it's not atomic operation on linux (and other unix systems) it's possible check using stat on filename, , fstat on filehandle, , comparing inodes returned each of functions.

this doesn't work on windows, less optimal.

<?php  $filename = './foo.txt'; $filehandle = fopen($filename, 'c'); $locked = flock($filehandle, lock_ex|lock_nb, $wouldblock);  if (!$locked) {     echo "failed lock file.";     exit(0); }  $unlinked = unlink($filename);  if (!$unlinked) {     echo "failed unlink file.";     exit(0); }  // comment out next line have 'file doesn't exist' result. file_put_contents($filename, "blah blah ");  $originalinode = null; $currentinode = null;  $originalstat = fstat($filehandle); if(array_key_exists('ino', $originalstat)) {     $originalinode = $originalstat['ino']; }   $currentstat = @stat($filename); if($currentstat && array_key_exists('ino', $currentstat)) {     $currentinode = $currentstat['ino']; }  if ($currentinode == null) {     echo "file doesn't exist."; } else if ($originalinode == null) {     echo "something went horribly wrong."; }  else if ($currentinode != $originalinode) {     echo "file handle no longer points current file."; } else {     echo "inodes apparently match, should never happen test case."; }  $closed = fclose($filehandle);  if (!$closed) {     echo "failed close file.";     exit(0); } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -