In a nutshell for those who don't want to read all of below:
I have given a website owner a PHP script and I am searching for a method to only allow that script to be run on each page of his website 4 times, not more.

Now for the full brief:

I am creating an ad network where publishers register their website, choose from 6 different ad sizes and receive a code in JS where they can place anywhere on their site.

So basically my problem is that I give the publisher a script for a specific ad size (300x250 for example) and he can place it anywhere in his site, but this can be abused, imagine someone takes this script and places it 1,000,000 times on his page, it will cause a lot of problems for me, my servers, and will be unfair method of making money.

I want to restrict this to only 4.

I have two pages right now with two different methods of approach:


- This one loads fast.
- Generally the JS is a PHP file that filters the available ads that meet the criteria of that box (meaning if we have 1,000 ads in our pool, it filters them based on the ones that are 300x250, the ones that are only "sport", etc. making only 100 that meet the criteria then it randomly selects 1 and then generates a JS that displays the ad)
- In the JS I have a global counter that checks and makes sure we are not more than 4 ads, if there is more than 4 ads it stops displaying.
- This wont be a good solution because already on the server PHP has been executed and the impression has been given to the user (not only that but my servers will also be flooded with requests), whether it is displayed or not. Therefore while I have stopped the display, I have not really stopped the attack on my server.
- In order to fix that problem I have done below:


- This one loads too slow.
- This basically has a JS that has a counter before running the above PHP. If the counter is less than 4 it runs the above file, if it is more than 4 it does nothing.
- Using the above, and encrypting it, my problem is resolved but it loads too slow (please compare the two).

How can I come with a method that is fast and stops such actions?