How to lock a file using PHP?
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
File locking is an important task. It restricts other users from changing a specific file. It allows only one user at a time to access or modify it. PHP provides the flock() method for portable advisory file locking. This was introduced with PHP version 4.0. This method provides options to mark the file for locking purposes. There are two kinds of locks we can make with flock- shared locks and exclusive locks. If you want to read only lock the file, use the shared lock, and if you want to lock the file for writing purposes, use the exclusive lock.
Syntax of flock()
flock($file_handler, $operation, $block)
$file_handler- It is a file handler pointer created by using fopen().
$operation- The lock operation can contain one of the following constants-
The $block is optional, set to 1 to block other processes while locking. The flock() function returns a boolean value. It returns TRUE if the file lock is retrieved successfully and FALSE otherwise.
flock() Exclusive lock (LOCK_EX) example
In the above code, we have opened a file 'text.txt' and assigned the file handler to $fh. Next, we lock the file using LOCK_EX (exclusive lock) in flock() function and write the $write variable to the file. The fflush() function flushes the output to the file. Finally, we released the locked file using LOCK_UN in the flock() function and closed the file handler. If you are using PHP version >= 5.3, you must manually unlock the file using the fclose() function.
When you execute the above code, it will append the given content at the end of the text file. Make sure to provide the write file path. If any error occurs during script execution, it will return the value provided in '$php_errormsg'.
PHP flock() Shared lock (LOCK_SH) example
As you saw in the above example, we have a locked file for writing. Here you will know how to read a locked file.
PHP flock() Non-blocking locking example
When the file is locked by another user, and you don't want to block while locking, use LOCK_NB as a bitmask to LOCK_SH or LOCK_EX.
need an explanation for this answer? contact us directly to get an explanation for this answer