file Locking

It can lead to a situation in which two or more people at a time will come to the site or just run the script. If it is, for example, counter that stores the number of visits in the file, these few people will want to save data to a file at the same time. This can lead to loss of data from this counter. But it is enough to apply the mechanism locks to prevent such a situation.Блоки бетонные для стен подвалов


The flock (int index, int operation) assumes the lock or it takes off, depending on the value of the second parameter. There are 2 types of locks: shared lock, used if the file is to be read and lock exclusive, assumed if the file is to be saved. The second function parameter can have these values:

LOCK_SH
to set up a shared lock
LOCK_EX Place
to set up an exclusive lock
LOCK_UN
to remove the lock, no matter what

How to use it in practice? Well function flock () returns true or false depending on whether they managed to set up a blockade or not. If a file is attached shared lock, it can be the file again lock to read, but to write anymore. If the established lock is exclusive, that no other script can no longer assume the lock until the lock is removed.
Depending on the application, you can react differently to the inability to LOCK. You can either stop or wait for the script to remove the clamp. In the case of counter one visit have no meaning in the face of having to wait for the completion of another script – will probably be a fraction of a second, but it is with this in different ways. As regards the database lock is waiting for the image block is a must.

Example
<?php

// Setup

// The name of the file containing the counter – relative to the directory in which
// Is the page where you want to count

$df = „lib / count.dat”;

// Attempt to open a file for reading

if (! ($fp = fopen @ ($df, „r”))) {

//If the file does not exist, it is initialized to the value 0

$count = 0;
}
else {// if it exists, its value is read and the file closed
$count = fgets ($fp, 100);
fclose ($fp);
}

// Increase the counter by 1

$count + = 1;

// Open file for writing

$fp = fopen ($df, „w”);

// Lock – if the file is already locked, the script closes it and ends
// action

if (! flock ($fp, LOCK_EX Place)) {
fclose ($ fp);
return;
} else {// If it is not locked, the lock occurs and record data
fputs ($fp, $ count);
flock ($fp, LOCK_UN);
fclose ($fp);
}

// Display the counter

echo $count;

?>

This file can be saved, eg. As count.php and in the right place on the page where you want the counter, type <? Include „count.php”?>. If you see errors like „Permission denied”, this means that something is wrong with the access rights to the data file, and if it does not yet exist, then the rights to the directory where you want the counter. The web server must have write access to the file / directory.

 

Cookies help us deliver our services. By using our services, you agree to our use of cookies. More Info | Close