tags:

views:

38

answers:

3

I have a maintenance script in PHP that updates and repairs the database. In theory, running two scripts simultaneously shouldn't be a problem, but I want to be extra safe by putting a lock in a variable in PHP. The problem, of course, is that I can't store it in a $_SESSION variable because sessions only apply to one user.

Is there any way I can store this lock in a variable? I'd prefer to not create and delete a file in case the server dies in the middle of the script.

+1  A: 

Since you're working with the database, you can lock the tables you need while the script runs. This will ensure exclusive database access.

MaxVT
+1  A: 

MySQL has GET_LOCK() function.

FractalizeR
A: 

Is there any way I can store this lock in a variable?

A variable is local to the current instance of php - so its an even worse solution than keeping it in the session.

I'd prefer to not create and delete a file in case the server dies in the middle of the script.

It's still probably the best place to put it. If the repair script does not complete then you probably want to step in and manually ensure that the data is consistent - you should also be blocking all other access to the resource betwen the time the operation starts and finishes successfully.

If its running from the command prompt, then you could search the process list:

$cmd=$argv[0];
$pid=getmypid();
$find="ps -ef | grep $cmd | grep -v grep | grep -v $pid";
$others=`$find`;

But this still carries the risk that the previous attempt failed and the data is corrupt.

C.

symcbean