防止直接访问 php 包含文件 [英] Prevent direct access to a php include file

查看:36
本文介绍了防止直接访问 php 包含文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 php 文件,我将专门用作包含文件.因此,当通过输入 URL 而不是被包含来直接访问它时,我想抛出一个错误而不是执行它.

I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.

基本上我需要在php文件中做如下检查:

Basically I need to do a check as follows in the php file:

if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");

有没有简单的方法可以做到这一点?

Is there an easy way to do this?

推荐答案

对于一般性的PHP 应用程序运行在您可能完全控制或可能不完全控制的 Apache 服务器上"情况的最简单方法是将您的包含放在一个目录中,然后拒绝访问您的 .htaccess 文件中的该目录.为了避免人们使用谷歌搜索的麻烦,如果您使用的是 Apache,请将其放在您不想访问的目录中名为.htaccess"的文件中:

The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:

Deny from all

如果您实际上完全控制了服务器(现在即使对于小应用程序来说比我第一次写这个答案时更常见),最好的方法是将您想要保护的文件粘贴在您的网络服务器目录之外是从.因此,如果您的应用程序在 /srv/YourApp/ 中,请将服务器设置为从 /srv/YourApp/app/ 提供文件,并将包含的内容放在 /srv/YourApp/includes,所以实际上没有任何 URL 可以访问它们.

If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.

这篇关于防止直接访问 php 包含文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆