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

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;
// -->

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'], '') !== false) { // if a match
	header("Location: /warning.html"); // redirect to /warning.html

Pretty much the simplest solution to this.

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

3 thoughts on “PHP, JavaScript: Stop and prevent others from framing your site or web page”

  1. 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. :))


  2. The javascript version is more elegant, I think 🙂
    I’ve always used a php version (with more code than yours and the same functionality, I must admit), but I think I’ll start using the JS version 🙂

Comments are closed.

Scroll to Top