Xaver
Xaver

Reputation: 11662

Count simultan requests in a PHP script

I'm searching for a way to count the current number of request to a certain file.

//start of script
$count = get_number_of_current_requests();
set_number_of_current_requests($count+1);

...

//end of script
$count = get_number_of_current_requests();
set_number_of_current_requests($count-1);

I've tried using a file to store the process and also a MySQL database entry but some tests failed and the value is not 0 after all processes are finished.

Is there "best way" to this kind of check?

Upvotes: 0

Views: 72

Answers (1)

alexis
alexis

Reputation: 50190

I don't know what else might be wrong with your code, but you have a small race condition at each update: Between the time you fetch the count and the time you store the new value, another thread might have done the same. You'll be better off delegating concurrency to MySQL, by asking for increment or decrement like this:

UPDATE stats SET connections to connections + 1 [ WHERE ... ]

The connection count never makes it to the PHP process. You only need to retrieve it when you want to display it.

Upvotes: 1

Related Questions