The file operating system is done in a networked environment and may have multiple client users accessing the same file on the server at the same time. When this concurrent access is generated, it is likely to corrupt the file. For example, a user is writing data to a file, and when it is not finished, other users write data to the file at this point, causing the data to be written in confusion. Also, when the user does not finish writing the data, other users get the contents of the file, and they get the incomplete data.
The flock () function is provided in PHP to use the lock mechanism (lock or release file) on a file. When a process adds a lock to the file, the other process will have to wait until the lock is released before the file can be accessed. This prevents data from being corrupted when the same file is accessed concurrently. The prototype of the function is as follows:
Copy Code code as follows:
BOOL Flock (int handle,int operation[,int&wouldblock])/Portable Consultation file Lockout
The first parameter handle must be a file resource that has already been opened, and the second parameter opeation is also required to specify which type to use. Operation can be one of the following values:
★lock_sh gets a shared lock (used when reading data from a file).
★LOCK_EX Gets an exclusive lock (used when writing data to a file).
★lock_un releases locks (both shared and exclusive locks are freed).
★lock_nb Additional locks (if you do not want the flock () to clog at lock time, add the lock after the lock above).
If the lock is blocked (the file that has been locked by flock () is locked again, the flock () function is suspended, the lock is blocked), or the optional third parameter can be set to 1, blocking other processes when the lock is made. The lock operation can also be released by Fclose (). In order for the flock () function to work, the file must be locked in the same way in all programs that access the file. The function returns True if it succeeds, and false if it fails.