Checking iframe is called from the approved domain?

RWC picture RWC · May 18, 2012 · Viewed 12.5k times · Source

Possible Duplicate:
How to limit display of iframe from an external site to specific domains only

What i want is simple. I want to prevent my website to be called from domains I did not approve. Let's say only a.com and b.com can have a page with an iframe calling my webapplication wwww.mydomain.com/myapp.php. How can I accomplish this?

1st I was thinking about my web appplication checking the domain of the iframe's parent. Maybe that is possible, but certainly not easy, because of cross-domain restrictions.

2nd I was thinking of having the requesting page on a.com and b.com execute a small PHP-script first which writes some info to a file or my database, so I know the requesting page is on one of the approved domains. The question is how to call and when to execute the script?

Is placing a script tag or image tag with a src attribute a good idea? That looks like a fairly simple solution to me and no PHP is required. The requesting page can be pure HTML.

Should it look like this:

<img src="http://wwww.mydomain.com/myapp.php" style="width: 0px; height: 0px;" alt="Not an image"  title="Not an image"/>

What do you advice?

Answer

RWC picture RWC · May 19, 2012

This is how I did it and it works like a charm. The average user won't be able to access my web application.

Nothing needs to be done on the approved domains. Sweet!

Thanks to dda and jackJoe ( How to limit display of iframe from an external site to specific domains only )

<?php

  define('MSG_NO_ACCESS', 'No access');

  $acceptedDomains = array('mydomain.com', 'a.com', 'b.com');
  $referer=get_domain($_SERVER['HTTP_REFERER']);

  if(!$referer || !in_array($referer,$acceptedDomains))
  {
     header('HTTP/1.0 403 Forbidden');
     exit(MSG_NO_ACCESS);
  }

function get_domain($url)
{
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) 
  {
     return $regs['domain'];
  }
  return false;
}

?>