
- PHP - Home
- PHP - Roadmap
- PHP - Introduction
- PHP - Installation
- PHP - History
- PHP - Features
- PHP - Syntax
- PHP - Hello World
- PHP - Comments
- PHP - Variables
- PHP - Echo/Print
- PHP - var_dump
- PHP - $ and $$ Variables
- PHP - Constants
- PHP - Magic Constants
- PHP - Data Types
- PHP - Type Casting
- PHP - Type Juggling
- PHP - Strings
- PHP - Boolean
- PHP - Integers
- PHP - Files & I/O
- PHP - Maths Functions
- PHP - Heredoc & Nowdoc
- PHP - Compound Types
- PHP - File Include
- PHP - Date & Time
- PHP - Scalar Type Declarations
- PHP - Return Type Declarations
- PHP - Operators
- PHP - Arithmetic Operators
- PHP - Comparison Operators
- PHP - Logical Operators
- PHP - Assignment Operators
- PHP - String Operators
- PHP - Array Operators
- PHP - Conditional Operators
- PHP - Spread Operator
- PHP - Null Coalescing Operator
- PHP - Spaceship Operator
- PHP Control Statements
- PHP - Decision Making
- PHP - If…Else Statement
- PHP - Switch Statement
- PHP - Loop Types
- PHP - For Loop
- PHP - Foreach Loop
- PHP - While Loop
- PHP - Do…While Loop
- PHP - Break Statement
- PHP - Continue Statement
- PHP Arrays
- PHP - Arrays
- PHP - Indexed Array
- PHP - Associative Array
- PHP - Multidimensional Array
- PHP - Array Functions
- PHP - Constant Arrays
- PHP Functions
- PHP - Functions
- PHP - Function Parameters
- PHP - Call by value
- PHP - Call by Reference
- PHP - Default Arguments
- PHP - Named Arguments
- PHP - Variable Arguments
- PHP - Returning Values
- PHP - Passing Functions
- PHP - Recursive Functions
- PHP - Type Hints
- PHP - Variable Scope
- PHP - Strict Typing
- PHP - Anonymous Functions
- PHP - Arrow Functions
- PHP - Variable Functions
- PHP - Local Variables
- PHP - Global Variables
- PHP Superglobals
- PHP - Superglobals
- PHP - $GLOBALS
- PHP - $_SERVER
- PHP - $_REQUEST
- PHP - $_POST
- PHP - $_GET
- PHP - $_FILES
- PHP - $_ENV
- PHP - $_COOKIE
- PHP - $_SESSION
- PHP File Handling
- PHP - File Handling
- PHP - Open File
- PHP - Read File
- PHP - Write File
- PHP - File Existence
- PHP - Download File
- PHP - Copy File
- PHP - Append File
- PHP - Delete File
- PHP - Handle CSV File
- PHP - File Permissions
- PHP - Create Directory
- PHP - Listing Files
- Object Oriented PHP
- PHP - Object Oriented Programming
- PHP - Classes and Objects
- PHP - Constructor and Destructor
- PHP - Access Modifiers
- PHP - Inheritance
- PHP - Class Constants
- PHP - Abstract Classes
- PHP - Interfaces
- PHP - Traits
- PHP - Static Methods
- PHP - Static Properties
- PHP - Namespaces
- PHP - Object Iteration
- PHP - Encapsulation
- PHP - Final Keyword
- PHP - Overloading
- PHP - Cloning Objects
- PHP - Anonymous Classes
- PHP Web Development
- PHP - Web Concepts
- PHP - Form Handling
- PHP - Form Validation
- PHP - Form Email/URL
- PHP - Complete Form
- PHP - File Inclusion
- PHP - GET & POST
- PHP - File Uploading
- PHP - Cookies
- PHP - Sessions
- PHP - Session Options
- PHP - Sending Emails
- PHP - Sanitize Input
- PHP - Post-Redirect-Get (PRG)
- PHP - Flash Messages
- PHP AJAX
- PHP - AJAX Introduction
- PHP - AJAX Search
- PHP - AJAX XML Parser
- PHP - AJAX Auto Complete Search
- PHP - AJAX RSS Feed Example
- PHP XML
- PHP - XML Introduction
- PHP - Simple XML Parser
- PHP - SAX Parser Example
- PHP - DOM Parser Example
- PHP Login Example
- PHP - Login Example
- PHP - Facebook Login
- PHP - Paypal Integration
- PHP - MySQL Login
- PHP Advanced
- PHP - MySQL
- PHP.INI File Configuration
- PHP - Array Destructuring
- PHP - Coding Standard
- PHP - Regular Expression
- PHP - Error Handling
- PHP - Try…Catch
- PHP - Bugs Debugging
- PHP - For C Developers
- PHP - For PERL Developers
- PHP - Frameworks
- PHP - Core PHP vs Frame Works
- PHP - Design Patterns
- PHP - Filters
- PHP - JSON
- PHP - Exceptions
- PHP - Special Types
- PHP - Hashing
- PHP - Encryption
- PHP - is_null() Function
- PHP - System Calls
- PHP - HTTP Authentication
- PHP - Swapping Variables
- PHP - Closure::call()
- PHP - Filtered unserialize()
- PHP - IntlChar
- PHP - CSPRNG
- PHP - Expectations
- PHP - Use Statement
- PHP - Integer Division
- PHP - Deprecated Features
- PHP - Removed Extensions & SAPIs
- PHP - PEAR
- PHP - CSRF
- PHP - FastCGI Process
- PHP - PDO Extension
- PHP - Built-In Functions
PHP Filesystem flock() Function
The PHP Filesystem flock() function is used to lock or release a file. This function allows us to perform a simple reader/writer model that can be used virtually on every platform.
The possible locks are LOCK_SH: Shared lock (reader). Allow other processes to access the file, LOCK_EX: Exclusive lock.Prevent other processes from accessing file, LOCK_UN: Release a shared or exclusive lock, and LOCK_NB: Avoids blocking other processes while locking.
These locks are used only in the current PHP process, and if the permission allows, other processes can modify or delete the PHP-locked file. This function is mandatory under Windows.We can use the fclose() function to release the lock operation, which can be automatically called when the script execution is completed.
This is a brief explanation of how it works −
- Open a File: To lock a file, you must first open it with fopen().
- Lock the File: Use flock() to lock the file. This ensures that no other script will be able to access it until you are done.
- Read or write in the file: execute the file actions (read or write).
- Open the File: To open the file once more when you are done, use flock().
- Close the Document: To close the file, use fclose().
Syntax
Below is the syntax of the PHP Filesystem flock() function −
bool flock ( resource $handle , int $operation [, int &$wouldblock ] )
Parameters
Here are the required and optional parameters of the flock() function −
Sr.No | Parameter & Description |
---|---|
1 |
handle(Required) It is the file pointer resource. |
2 |
operation(Required) The type of lock. It can be − |
3 |
wouldblock(Required) The third argument is optional and is set to 1 if the lock blocks. |
Return Value
It returns TRUE on success, or FALSE on failure.
PHP Version
The flock() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7, PHP 8.
Example
So first we will see the basic usage of the PHP Filesystem flock() function to make an exclusive lock on the given file. Here is the simple demonstration of this example −
<?php $file = fopen("/PhpProject/sample.txt", "w+"); // exclusive lock if(flock($file, LOCK_EX)) { fwrite($file, "flock function"); // release lock flock($file, LOCK_UN); echo $file; } else { echo "Error locking file!"; } fclose($file); ?>
Output
When you run this script, you will see something like the below result −
Resource id #12345
Example
So now we will see how we can write the content and read the written content after using the flock() function.
<?php $file = fopen("/PhpProject/sample.txt", "w+"); // Open the file for reading and writing // exclusive lock if(flock($file, LOCK_EX)) { fwrite($file, "flock function"); // release lock flock($file, LOCK_UN); } else { echo "Error locking file!"; } fclose($file); // Close the file // Reopen the file to read its content $file = fopen("/PhpProject/sample.txt", "r"); $content = fread($file, filesize("/PhpProject/sample.txt")); fclose($file); echo $content; // Outputs the content of the file ?>
Output
This will produce the following result −
flock function
Example
Let's assume we have a script that logs messages to a file. So with the help of flock() function we can ensure that at a time only one process can write to the file.
In our code, the flock($file, LOCK_EX) will try to get an exclusive lock and the flock($file, LOCK_UN) will release the lock after writing process is done.
<?php $logFile = "/PhpProject/log.txt"; $message = "This is a log message.\n"; // Open the log file in append mode $file = fopen($logFile, "a+"); // Try to get an exclusive lock for writing if (flock($file, LOCK_EX)) { // Write the message to the log file fwrite($file, $message); // Release the lock flock($file, LOCK_UN); echo "Message logged successfully."; } else { echo "Error locking file!"; } fclose($file); // Close the file ?>
Output
If the lock is successful and the message is written, the output will be −
Message logged successfully.
If there is an error in locking the file, the output will be −
Error locking file!
Note
If flock() is unable to lock the file, it will return false so you can handle this in your code to stop undesirable behavior.
Summary
The flock() function in PHP is used to control file locking. By using file locking to stop multiple scripts from accessing the same file at a time. So using this we can prevent data corruption.