简体   繁体   English

仅允许通过 iFrame 访问 URL 并防止在 PHP 中直接访问

[英]Allowing URL access only via an iFrame and prevent from direct access in PHP

I have a website folder with some content in PHP.我有一个网站文件夹,里面有一些 PHP 内容。 And I want it to be accessed only via iframe.我希望它只能通过 iframe 访问。 And want to prevent using direct URL access.并希望阻止使用直接 URL 访问。

Allow access <iframe src="example.com/chocos.php"></iframe>允许访问<iframe src="example.com/chocos.php"></iframe>

And redirect accessing the example.com/chocos.php URL if directly accessed.如果直接访问,则重定向访问example.com/chocos.php URL。

I have added a javascript for this purpose.为此,我添加了一个 javascript。

<script>if(window==window.top) { window.location.href = "/"; } </script>

But I want to do this using PHP.但我想使用 PHP 来做到这一点。 Can anyone help me solve this problem?谁能帮我解决这个问题?

You can achieve that with php using cookies:您可以通过 php 使用 cookie 来实现:

On the main page that have the iframe code, save a new cookie without setting an expiration date for it:在包含 iframe 代码的主页上,保存一个新的 cookie 而不为其设置过期日期:

setcookie("allowAccess", 1);

then, on the file that is loaded into the iframe, "chocos.php" in your case:然后,在加载到 iframe 的文件上,在您的情况下为“chocos.php”:

if(isset($_COOKIE['allowAccess'])
    {
       //your content here;
    }
else
    {
       //your redirection here
    }

so if the user doesn't visit the main page, the alloweAccess cookie won't set in the browser, so the iframe page will do the redirection as you want.因此,如果用户不访问主页,则不会在浏览器中设置 alloweAccess cookie,因此 iframe 页面将根据需要进行重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM