A smarter iFrame with PHP

Depending on site design, it can often be much quicker to embed dynamic content  in an iframe which already has your site’s header and footer. The problem with this approach is that _blank links pointing to said content will not open in the iframe, but instead in a window without your site’s design. Here’s how to create a smart iframe to handle those requests.

If we code our iframe in php, we can just pass it the URLs we want it to display as parameters. This way when we have a link pointing to the content we want to open within the ifame, we can form it like this:

http://...com/myiframe.php?url=http://mycalendarurl

Our iframe can $_GET the URL as a passed parameter and display it in between your site’s header and footer so it looks all fancy like. To pull this off we’ll have to urlencode() the parameter part of our URL so it looks like this:

http://...com/myiframe.php?url=http%3A%2F%2Fmyurl.com%2Fmycontent.html

As shown above, we essentially prepend the path to our iframe to a urlencoded link which would ordinarily just get us the content. Here’s the PHP code we use in the iframe page:

<?php
$url = $_GET['url'];
if (isset ($url)) { // decode the url and display it in the iframe
echo '<iframe ... src="'.urldecode($url).'"></iframe>';
} else { // display a static page if no url parameter was received
echo '<iframe ... src="http://myurl.com/mycontent.html"></iframe>';
}
?>

The code above checks to see if there is a URL parameter being passed (further checking could be done here). If it finds one, it displays its content inside the iframe, otherwise it displays a static page (in case someone accesses the iframe directly).

That’s it.


Posted

in

by

Comments

5 responses to “A smarter iFrame with PHP”

  1. Php Moz Avatar

    It’s actually a cool and helpful piece of information. I’m satisfied that you just shared this useful info with us. Please stay us up to date like this. Thanks for sharing.

  2. Anthony Avatar
    Anthony

    Usefull! Thanks for sharing, I had to search a bit to find out some php codes that you used but I get it!

  3. Pere_Knockout Avatar
    Pere_Knockout

    Hi,
    I have one question. How to resolve the problem of requsting url which in the get parameter contains the requesting url itself?? For example, instead of
    http://example.com/myiframe.php?url=http://mycalendarurl to have http://example.com/myiframe.php?url=http://example.com/myiframe.php?url=http://mycalendarurl?

    It will open the site in iframe and that iframe will open another iframe. How to avoid this?

  4. Tejesh Avatar
    Tejesh

    Awesome answer!! It solved my 10 days problem. Thank you a lot!!

  5. er Avatar
    er

    thank you