Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check the file is opend before rename

Tags:

php

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.

like image 464
Bharanikumar Avatar asked Mar 24 '23 05:03

Bharanikumar


1 Answers

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.

like image 106
Prix Avatar answered Apr 02 '23 21:04

Prix