PHP, JavaScript: Stop and prevent others from framing your site or web page

by Yang Yang on August 30, 2009

Share This Article:
Subscribe to Kavoir: blog feed

Though it does increase traffic and the pageviews, it doesn’t feel quite good with someone who’s loading your website or page as a part of theirs in the form of a <frame> or <iframe>, leeching your content as part of theirs. To prevent them from loading your pages this way, and make the visitor browser to load the entire window with your site on the "_top" level, you need some javascript:

<script type="text/javascript">
<!--
	if (self.location.href != top.location.href) {
		top.location.href = self.location.href;
	}
// -->
</script>

Basically, this snippet checks if the URL location of this frame is the same with that of the top frame that is the browser window, if negative, meaning your site or page is being framed from another site, the entire window is then loading your site as the only page.

On the other hand, you can also do this by the help of PHP or a combination of both. Just check the global variable $_SERVER['HTTP_REFERER'] against the URL of a particular leeching site, if it’s a match, stop serving the content and redirect the visitors to a warning page so that they know they can come to your website directly instead of from a frame or iframe:

if (strpos($_SERVER['HTTP_REFERER'], 'leechsite.com') !== false) { // if a match
	header("Location: /warning.html"); // redirect to /warning.html
	exit();
}

Pretty much the simplest solution to this.

Interesting: Make sure you give a read to this Q&A thread at Stack Overflow.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 1 comment… read it below or add one }

Alexandru Stefan April 13, 2011 at 9:09 pm

Cooooool way of protecting my site. I could make that visitors of a site that wraps my site to be redirected to a warning page where i say that guy that wraps me is a loser and what’s the original page where people should go. :))

Thanks!

Reply

Leave a Comment

Previous post:

Next post: