Hi, I was wondering if it is possible in PHP to check if a file is in use by a third party program? I have the scenario where .dia files are dynamically created within a directory. This directory is systemically scanned every 60 seconds by a CRON job, which runs a PHP script. At the moment the script reads in any files in the directory and inserts their data into a database. Once the file has been read it is moved to another directory. Is it possible to check whether a file is open so I can adapt the script not to move the file? Thanks.
I guess you would need to create some sort of Lock on the file and then have PHP check if the file is currently locked. I don't know how the files are actually created though, but there is a PHP function called flock which is a reader/writer model. http://php.net/manual/en/function.flock.php
Thanks for your reply The files are generated by a bespoke third party software. Some files will take a couple of seconds to generate, whereas others can take hours - there is no set time for how they take. The issue is how do I get my PHP script to determine whether the file is currently open and in the process of being generated? Thanks.
There might be other ways to do this - involving somewhat different approaches - first, is it in any way possible to have the third-party software name the files something else while they're being generated? Ie, something like .dia_new, or anything like that? If that's not possible, how about creating the files somewhere else, and not move them until they're finished? (It's not possible to move a file which is in use)? Then they will definitely not be in use when PHP can read them.
Two possible solutions (both Linux based), both will show you if someone is accessing the files (being written to) or completed: $ lsof /location/of/file.txt COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME bash 21310 username cwd DIR 8,1 4096 5054467 /location/of/file.txt $ fuser /location/of/file.txt /location/of/file.txt: 21310 Code (markup): You can execute those within PHP if you need to as well using exec/etc..