How to do something every x clicks in PHP

There are many situations where you need to do somthing sometimes but not on every single request. There are many ways to archive this, you could implement a DB or file based counter. But if it is not important that it happens exactly after x request then this simple trick or snippet might help you out when you find yourself in a situation like:

How do I cache my data for x requests?

Or:

Hmm how do I build a good performing session garbage collection?

Or my favorite:

Im hosting a porn website, but im poor and can't afford to count every click.. Soluzzaannss?

Yes Sir there is a solution! Today must be your lucky day. I offer you the solution for just 5 bucks. Just for YOU! the other idiots have to pay the full price ;)

So please click on the buy button below.

Buy the solution for 5$


You are only allowed to read the solution after this line if you payed me the 5$, or I will do evil bliki blinki virus stuff with your computer!?!

Ok enough of my not funny bullshit.

 The Solution

// deletes the cache folder ca. every 25 executions
if ( mt_rand( 1, 25 ) == 1 )  
{
    unlink( 'my/porn/cache/folder/' );
}

Isn't that little fuck beautiful?

Let me shortly explain that before the shit storm starts:

Of course this will not execute your code exactly every 25th request. But with a lot of data it will. Okey this sounds confusing let me prove that with an example:

$steps = 0;

$executions = array();

for( $i=0; $i<=100000; $i++ )  
{
    if ( mt_rand( 1, 25 ) == 1 ) 
    {
        $executions[] = $steps; $steps = 0;
    }

    $steps++;
}

$sum = 0;

foreach( $executions as $steps )  
{
    $sum += $steps;
}

var_dump( $sum / count($executions) );  

Will result in values like:

float(25.414590747331)  
float(24.77783287875)  
float(25.315016459863)  

You probably alredy got what I want to point out. Obviously The avarage of steps or request needed until the random value matches 1 is always the count of possibilities. Every value in your random rage is equaly probable to be picked. So in the end your code is executed every x (your chosen count of possibilities) time.

I use this system also for CCF's garbage collection of the sessions: https://github.com/ClanCats/Core/blob/9d4f7ce2ad42a42818e1b5bb1e754ac73ed59ef3/src/bundles/Session/Manager.php#L161

First time I saw that idea in the Kohana PHP Framework, but i could not find it. After a quick search i found that the FuelPHP framework implements a similar pattern:
https://github.com/fuel/core/blob/7dc50ccabbe9e9296991234cc4d1755cacba3bfd/classes/session/db.php#L256

Thanks for reading :)

Mario Döring

Mario Döring

http://clancats.ch

Software Engineer, ClanCats Dude, cineman.ch Developer and general Idiot.

View Comments
Navigation