Reputation: 25733
I have cleanup script, which move the XLS files from one place to another. for this file moving process, I have used the rename function. This script is working fine. but when the XLS file is open, when I try to move that xls, I am getting error which simply say Can not rename sample.xls. But I would like to add the functionality like, Check the XLS is open before initiate rename function.
I believe this is function call flock
but this is applicable for TXT file alone.
How to check XLS file is opened before call the rename function.
Upvotes: 4
Views: 1555
Reputation: 19528
One simple thing you could try is to use flock
to acquire a Exclusive Lock on the file and if it fails you will know 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 the existence of the locking file excel usually creates when a file is being 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 is usually name with the prefix ~$
as for old excel files I believe 2003 and older the lock files are saved on the temp folder with a random name like ~DF7B32A4D388B5854C.TMP
so it would be pretty hard to find out.
Upvotes: 4
Reputation: 8179
You should use flock()
. This puts a flag on the file so that other scripts are informed that the file is in use. The flag is turned off either intentionally using fclose
or implicitly by the end of the script.
Upvotes: 2