Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow a page to only load in an iframe

How can I allow my PHP file to only load in an iframe?

For example:

  • Prevent direct access: example.com/Loader.php
  • Allow iframe access: <iframe name="TEST" src="Example.com/Loader.php"></iframe>
like image 200
hamid Avatar asked Mar 29 '13 22:03

hamid


2 Answers

You wouldn't use PHP for that. Try javascript.

if(window==window.top) {
    // not in an iframe
}
like image 177
Richard Avatar answered Oct 04 '22 14:10

Richard


Supposing that you have file file1.php that have an iframe within and this iframe point to file2.php

code supposed for the file file1.php:

<iframe src="file2.php" width="500" height="100"></iframe>

content of the file file2.php:

<?php
echo "This file exist in an iframe";
?>

So let update the file1.php to the following code :

<?php
session_start();
$_SESSION['iframe'] = md5(time()."random sentence");
?>
<iframe src="file2.php?internal=<?php echo $_SESSION['iframe'];?>" width="500" height="100"></iframe>

and also update the file2.php as following :

<?php
session_start();
if(!isset($_SESSION['iframe']) || !isset($_GET['internal']) || $_SESSION['iframe'] != $_GET['internal'])
    {
        die("This page can be accessed just from within an iframe");
    }
unset($_SESSION['iframe']);
//Continue processing using your own script
?>

Try this and tell me if this works or not :)

like image 29
Last Breath Avatar answered Oct 04 '22 15:10

Last Breath