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?


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;


$sum = 0;

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

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

Will result in values like:


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:

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:

Thanks for reading :)

Mario Döring

Mario Döring

Solution Architect creating the black magic for Cineman, handyman for ClanCats, useless PHP things Entrepreneur and general Idiot.

View Comments