Lecko
Lecko

Reputation: 1425

Lockfile in PHP

I have PHP script that should be run only once at the moment. If someone else tries to launch it again while it is already working, the second process should immediately die with error message.

When I try to launch the code below at the second time, it waits for 10 seconds and prints nothing instead of immediate printing of error message. What's wrong with it?

NB: script is launched from browser! In console everything works correctly

<?
$fh = fopen(__FILE__, 'r');
if(! flock($fh, LOCK_EX) ){
    fclose($fh);
    die("Operation is already performed");
}
else{
    sleep(10); //this is "some operation" stub
    flock($fh, LOCK_UN); // unlock the file
    fclose($fh);
}

?>

Upvotes: 3

Views: 1657

Answers (1)

epicdev
epicdev

Reputation: 406

From the manual: "Only a single process may possess an exclusive lock to a given file at a time."

Anyway, this is a bad way to implement locking. For example, what you can do is to write something in a file and delete it when your script stops. That way, you can check if there is an other process running by checking if the file is empty.

Upvotes: 4

Related Questions