2013-03-29 54 views
2

如何让我的PHP文件仅加载iframe允许页面只加载iframe

例如:

  • 避免直接访问:example.com/Loader.php
  • 允许的iframe访问:<iframe name="TEST" src="Example.com/Loader.php"></iframe>
+0

你可能可以在js中做到这一点,但不能与任何html/php脚本 – Class

回答

8

你不会使用PHP这一点。试试javascript。

if(window==window.top) { 
    // not in an iframe 
} 
+0

如果有人在浏览器中关闭JS,怎么办? – Grasper

+0

如果仅在iframe中显示文件至关重要,则除非您确定,否则请阻止对其进行访问。知道页面是否加载到iframe中的唯一方法是检查客户端。 – Richard

+0

这应该被标记为答案。 –

5

假设你有文件file1.php有内iframeiframefile2.php

代码应该对文件file1.php:文件的

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

内容file2.php

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

因此,让更新file1.php下面的代码:

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

,并同时更新file2.php如下:

<?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 
?> 

试试这个,告诉我如果这工作或不:)

+0

这仍然允许页面在iframe之外打开。只要file1.php没有刷新,就可以用正确的内部变量执行file2.php。 –

+0

如何在iframe之外打开它? 如果$ _GET ['internal']的值不会从别处生成? 请您在说明中更清楚一点,或者您只是指向劫持会话? 请注意,不要忘记我将$ _SESSION ['iframe']变量取消设置,所以我无法真正找到它是如何被访问的,因为你说的请解释你的意思:) –

+0

如果有人将URL复制到file2。来自file1.php源代码的php,他/她可以将其粘贴到地址栏中,并且file2.php可以打开。 –