CakeFest 2024: The Official CakePHP Conference

SplFileObject::flock

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::flockVerrouille ou déverrouille un fichier

Description

public SplFileObject::flock(int $operation, int &$wouldBlock = null): bool

Verrouille ou déverrouille un fichier, de la même façon que la fonction flock().

Liste de paramètres

operation

Le paramètre operation peut prendre une des constantes suivantes :

  • LOCK_SH pour acquérir un verrou partagé (lecture).
  • LOCK_EX pour acquérir un verrou exclusif (écriture).
  • LOCK_UN pour déverrouiller le fichier (partagé ou exclusif).

Il est aussi possible d'ajouter LOCK_NB en tant qu'un masque binaire à l'une des opérations ci-dessus, si flock() ne devrait pas bloquer lors de la tentative de vérrouillage.

wouldBlock

Définit à true si le verrou doit être bloquant (condition pour l'errno EWOULDBLOCK).

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Exemples

Exemple #1 Exemple avec SplFileObject::flock()

<?php
$file
= new SplFileObject("/tmp/lock.txt", "w");
if (
$file->flock(LOCK_EX)) { // verrou exclusif
$file->ftruncate(0); // coupe le fichier
$file->fwrite("Écrire quelque chose ici\n");
$file->flock(LOCK_UN); // libère le verrou
} else {
echo
"Impossible de récupérer le verrou !";
}
?>

Voir aussi

add a note

User Contributed Notes 2 notes

up
4
digitalprecision at gmail dot com
13 years ago
For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.
up
0
Ahmed Rain
1 year ago
@digitalprecision What you said is not completely true, ftruncate(0); is needed if there was a write to the file before the lock is acquired. You also may need fseek(0); to move back the file pointer to the beginning of the file

<?php
$file
= new SplFileObject("/tmp/lock.txt", "w");
$file->fwrite("xxxxx"); // write something before the lock is acquired
sleep(5); // wait for 5 seconds

if ($file->flock(LOCK_EX)) { // do an exclusive lock
$file->fwrite("Write something here\n");
$file->flock(LOCK_UN); // release the lock
} else {
echo
"Couldn't get the lock!";
}
?>

"lock.txt" content:

xxxxxWrite something here
To Top