PHP Verify that the file opens before renaming

I have a cleanup script that move XLS files from one place to another. For this process of moving the file, I used the rename function. This script is working fine. but when the xls file is open, when I try to move this xls, I get an error that simply says “Cannot rename sample.xls”. But I would like to add features like: check that XLS is open before the rename function starts.

I believe this is a call to the flock function, but this only applies to the TXT file.

How to check the .xls file opens before calling the rename function.

+4
source share
3 answers

One simple thing you can try is to use flock to get an exclusive file lock and if it doesn’t work, you will know that the file is being used:

 <?php $fp = fopen('c:/your_file.xlsx', 'r+'); if(!flock($fp, LOCK_EX)) { echo 'File is being used...'; exit(-1); } else { fclose($fp); // rename(...); } 

An alternative would be to check for the existence of a lock file. Normally excel creates when a file is used:

 <?php $file = 'c:/testfile.xlsx'; $lock = 'c:/~$testfile.xlsx'; if (file_exists($lock)) { echo "Excel $file is locked."; } else { echo "Excel $file is free."; } 

The hidden file usually has a name with the prefix ~$ , as for old excel files, which, it seems to me, in 2003 and older, lock files are stored in the temp folder with a random name like ~DF7B32A4D388B5854C.TMP , so it would be pretty hard to find from .

+3
source

You must use flock() . This puts the flag in the file so that other scripts are informed that the file is being used. The flag is turned off either intentionally using fclose , or implicitly at the end of the script.

+2
source

Use file locking, for example:

 flock($file,LOCK_EX); 

see this

+1
source

Source: https://habr.com/ru/post/1490859/


All Articles