Php check if file is in use

how to know if file is still open for writing

i have a function that writes to a file , how can i using another script check if the file is being used for writing or it is closed ? Edit : this file might be opened for writing by other script/application/system . thank you .

3 Answers 3

You should use flock in both scripts. 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.

While flock is the answer (or dio_fcntl ), flock only provides an advisory lock. You have to coordinate everywhere with flock. Any other script not using flock can manipulate the file at any time.

@jasonbar Hence by «in both scripts». After your first comment, I had updated my answer to reflect your excellent point.

@Rohan, this covers cross script / application cases. What do you mean by «system»? Another physical (or virtual) machine?

If you’re on Unix, your system might have the lsof («LiSt Open Files») command installed. The «FD» column in the output indicates whether the file was opened for reading, writing, or both.

I’d like to point out that any process of the form «check to see if file X is open for writing, if so do something. » is subject to a race condition. Some other process could open the file after you’ve checked, but before the action was started.

@Ronan: In Windows, it’s easier — the LockFile function allows guaranteed exclusive access to a file (or even part of a file). Most Unix filesystems only provide advisory locks, which aren’t necessarily respected by other processes beyond your control, so file locking is not a good design choice for that environment. lsof or flock() may get you part of the way there.

I’d say just use the file open function, if it returns false, then the file’s obviously still open.

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

Detecting if a PHP File is Being Used

It’s important to note that certain machines utilizing virtual paths may generate varying paths across different php components. Furthermore, if you’re interested in determining whether a file is currently being utilized by another command, you can utilize a linux command to check for an open handle associated with the file and being used by another process. It’s worth mentioning that these commands are exclusive to linux and cannot be executed on windows.

Php: check if a file is open

To indicate that a file is in use, you may generate a «filename.lock» or «filename.lck» file. When the file is no longer being used, simply remove the «filename.lock» or «filename.lck» file.

Читайте также:  scale()

The presence of a file named «filename.lock» or «filename.lck» signifies that the file is locked and needs to be checked.

If you are using a Unix operating system, it is possible to adopt an approach similar to this.

  1. Create a bash script that resembles the following code: lsof | grep /absolute/path/to/file.txt

    You can also parameterize that

  2. Recall that script from php

Keep in mind that the bash script’s status will be 0 when there are no open files and 256 (1) in all other cases.

Fopen — PHP check if file contains a string, PHP check if file contains a string. Ask Question Asked 10 years, 6 months ago. Modified 6 months ago. Viewed 111k times ps, by more efficient, he means probably slower (unless file_get_contents use so much ram that you start swapping, in which case this might be faster), but should use significantly less …

How to detect if a file is being included or directly ran

While it may not be the most effective approach to prevent users from requesting an include file directly, verifying if the script is the parent of the PHP process can prove useful in various situations such as AJAX modules. However, I won’t delve into that topic at the moment.

if (__FILE__ == get_included_files()[0]) // Doesn't work with PHP prepend unless calling [1] instead. if (__FILE__ == $_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_FILENAME']) // May not work on Windows due to mixed DIRECTORY_SEPARATOR (machine specific) if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) // Doesn't work with files with the same basename but different paths if (defined('FLAG_FROM_A_PARENT')) // Works in all scenarios but I personally dislike this if (realpath(__FILE__) == realpath($_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_FILENAME'])) // Should work flawlessly 

When using machines that utilize virtual paths, it is important to note that various PHP components may produce distinct paths. To address this concern, it is recommended to use realpath().

Ensure that the scripts provided are not reachable through HTTP. This can be achieved by either safeguarding the subdirectory or relocating them above the document root.

In case you are unable to perform that action, consider using define() in your primary script and IS_INCLUDED in your auxiliary script. Also, ensure that the constant exit; is present in the main script and defined() in the included script.

In my code, I utilize a sentinel constant that is declared in the script that includes it, and the script being included searches for its presence.

/* main.php */ define('SENTINEL', 1); include "included.inc.php" /* included.inc.php */ if (!defined('SENTINEL')) die("Wanted to be smart?? Nice try."); 

PHP check file extension, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Test if file is locked

if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) < if ($wouldblock) < // another process holds the lock >else < // couldn't lock for another reason, e.g. no such file >> else < // lock obtained >

Utilize LOCK_NB from the documentation to make an asynchronous effort to acquire the lock. If unsuccessful, assess the $wouldblock parameter to determine if the lock is held by something else.

if(stream_get_meta_data($fp)['blocked']) echo 'file is locked'; else echo 'file is not locked'; 
if (!flock($file, LOCK_EX)) < throw new Exception(sprintf('File %s is locked', $file)); >fwrite($file, $write_contents); 

Php — How to detect if a file is being included or directly, For the first solution, it might be dangerous, if you don’t implement the second too. If you’re in a shared environment, the server can have its configuration changed (also erroneously) in a way that the subfolder protection no longer works, or you can move your script to another server which has different …

Читайте также:  Вывод значений ассоциативного массива php

How to check if a file is BEING used, i.e. some command is being executed on the data in that file?

An approach proposed on https://stackoverflow.com/a/6767891/2032943 involves utilizing inotifywait to monitor events and respond accordingly.

To verify if a file is currently in use by another process, you can utilize the Linux lsof command to check for an open handle associated with the file.

Please be aware that the commands mentioned are exclusive to Linux and cannot be executed on Windows.

Php — How to check if a file is BEING used, i.e. some, Using an infinite while() loop, continuously keep checking if the directory has any files of that particular extension (e.g. check if the directory has any *.xml files). I can use the PHP glob() function. If yes, then in a foreach loop, read data from each file and load it into the database. Once a file’s data has been … Usage examplelsof | grep Feedback

Источник

PHP check if filename is in use and then add number on upload

I’m trying to make a «send email» form which uploads files to a folder before the email is sent. The path to the files are then shown in the email, but if the files DO exist i don’t want them to be overwritten, but i want to have a number added. I have composed this tiny code, but it doesn’t work! The error says:

Parse error: syntax error, unexpected ‘$name_of_uploaded_file’ (T_VARIABLE) in /customers/8/5/6/HOMEPAGE/httpd.www/php/mailtest2.php on line 49

The script below now upload a file if the file does not exist. If the file does exist nothing happens. The script ends at it should. The script have been modified to what caused it not to ad «_1» to filename and save file in folder. Now it saves the file in folder and comes up with error: Error while copying the uploaded file Can someone please explain to me what i do wrong? Now all code is shown to debug this:

 $upload_folder = $varfoldername; //Get the uploaded file information $name_of_uploaded_file = basename($_FILES['uploaded_file']['name']); //Validations //----- Check if files exists and adds _X to it ----- $original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME); $extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION); $FileCounter = 0; while (file_exists($varfoldername.$name_of_uploaded_file)) < $FileCounter++; $name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension; >//copy the temp. uploaded file to uploads folder $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; $tmp_path = $_FILES["uploaded_file"]["tmp_name"]; if(is_uploaded_file($tmp_path)) < if(move_uploaded_file ( $tmp_path,$path_of_uploaded_file )) < die("Error while copying the uploaded file"); >> //Validate size requirements $size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;//size in KBs if($size_of_uploaded_file > $max_allowed_file_size ) < die("Fejl: Filen er for stor"); >//------ Validate the file extension ----- //get the file extension of the file $type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1); $allowed_ext = false; for($i=0; $i > if(!$allowed_ext) < die("The uploaded file is not supported file type. \n Send venligst filer af følgende type: .implode(',',$allowed_extensions)"); >$email = $_POST['email']; $phone = $_POST['phone']; $call = $_POST['call']; $company = $_POST['company']; $type = $_POST['type']; $adress = $_POST['adress']; $hesteid = $_POST['hesteid']; $hestenavn = $_POST['hestenavn']; $message = $_POST['message']; $areacode = $_POST['areacode']; $land = $_POST['land']; $formcontent=" Fra: $company \n Navn: $name \n Adresse: $adress , $areacode \n Land: $land \n Telefon: $phone \n Ringes op: $call \n Type: $type \n Hoppens navn og ID: $hestenavn , $hesteid \n Besked: \n $message \n Vedhæftede filer: \n $path_of_uploaded_file"; $recipient = "simon@secret.dk"; $subject = "Besked fra hjemmesiden"; $mailheader = "Fra: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); header('Location: thank_you.shtml'); ?> 

Источник

Читайте также:  Reading excel file with python

php: check if a file is open

I’m writing a document managment system. One of the features that has been requested is that users be able to cause the system to copy certain files to a location that both the users and php have access to. From here the user will be able to directly edit the files. What needs to happen is that the edited file must be automatically saved to the document management system as a new version. My question is with regards to this last point. I have a page that allows the user to view all versions of a specific file. I was thinking that what would be cool would be to have things that when this page is accessed by anyone then php checks if there is an associated file that was edited and is now closed and simply move it to the right place and give it version info. Would this be possible? For example if a user is editing a file using MS Word, would php be able to know if that file is in use? If yes, how? Another alternative is to just grab all files that were edited periodically (during the witching hour, for example) and also have a handy ‘synchronise’ button that users can click to signal that they are done. here’s some stuff I’ve tried: flock: i thought it mich return false for files that are in use. mistaken fstat: doesn’t return anything useful as far as I can tell unlink: I thought I might make a copy of the file then try unlink the original(user edited one). it turns out unlink works on stuff that is open any ideas? Also, it needs to work on windows and linux. Here’s some clarification for them what need: if andrew were to click the ‘edit’ button corresponding to a word file then the word file would be copied to some location. Andrew would then edit it using MS word, save his changes (possible more than once) and close it. That is all I want Andrew to do. I want my code to see that the file is closed then do stuff with it

the modified time was when it was modified, not closed. usually people save as they close things but I cant ever be sure that they didn’t save stuff without editing

Источник

Оцените статью