Using PHP session_id() to Make Sure iframe is Generated by Our Server Dynamically
- by Michael Robinson
We use iframes to show ads on our site.
Iframes are used to allow us to keep the ad generation code and other site modules separate.
As we track ad views on our site, and need to be able to keep an accurate count of which pagetype gets what views, I must ensure that users can't simply copy-paste the iframe in which the ad is loaded onto another site. This would cause ad count to become inflated for this page, and the count would not match the view count of the page the iframe "should" be displayed in.
Before anyone says so: no I can't simply compare the page view count with the ad view count, or use the page view count * number of ads per page, as # of ads per page will not necessarily be static.
I need to come up with a solution that will allow ads to be shown only for iframes that are generated dynamically and are shown on our pages.
I am not familiar with PHP sessions, but from what little reading I have had time to do, the following seems to be to be an acceptable solution:
Add "s = session_id()" to the src of the ad's iframe.
In the code that receives and processes ad requests, only return (and count) and ad if s == session_id().
Please correct me if I'm wrong, but this would ensure:
Ads would only be returned to iframes whose src was generated alongside the rest of the page's content, as is the case during normal use.
We can return our logo to ad calls with an invalid session_id.
So a simple example would be:
One of our pages:
<?php session_start(); ?>
<div id="someElement">
<!-- EVERYONE LOVES ADS -->
<iframe src="http//awesomesite.com/ad/can_has_ad.php?s=<?php echo session_id(); ?>></iframe>
</div>
ad/can_has_ad.php:
<?php session_start(); ?>
if($_GET['s'] == session_id()){
echo 'can has ad';
}
else{
echo '<img src="http://awesomesite.com/images/canhaslogo.jpg"/>';
}
And finally, copied code with static 's' parameter:
<!-- HAHA LULZ I WILL SCREW WITH YOUR AD VIEW COUNTS LULZ HAHA -->
<iframe src="http//awesomesite.com/ad/can_has_ad.php?s=77f2b5fcdab52f52607888746969b0ad></iframe>
Which would give them an iframe showing our awesome site's logo, and not screw with our view counts.
I made some basic test cases: two files, one that generates the iframe and echos it, and one that the iframe's src is pointed to, that checks the 's' parameter and shows an appropriate message depending on the result. I copied the iframe into a file and hosted it on a different server, and the correct message was displayed (cannot has ad).
So, my question is:
Would this work or am I being a PHP session noob, with the above test being a total fluke?
Thanks for your time!
Edit:
I'm trying to solve this without touching the SQL server