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.

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?

推荐答案

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

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相关问答推荐

WordPress:将自定义单选输入字段添加到用户配置文件

RediSearch PHP希望我在每次使用时定义所有字段

如何在php网站代码中清理浏览器缓存

如何在WordPress REST API中判断应用程序密码

在WooCommerce中只允许高价产品的BACS付款

PHP按另一个二维数组的排序顺序对二维数组进行排序

打折时更改 Woocommerce 产品名称

如果所有请求都通过index.php路由,如何使用htaccess文件强制使用HTTPS?

将自定义字段添加到管理产品中 WooCommerce 3.2+ 中的快速编辑

对 WooCommerce 购物车和 checkout 中显示的运输方式进行排序

通过添加计数器修改文本区域表单中的重复值

主机中未检索用户表数据

图像未在 Laravel Ajax Crud 中显示

如何搜索和替换 XML 文件中的一段文本?

WooCommerce – 在新订单邮箱通知中显示产品分类计数

WooCommerce - 调用功能ID不正确.不应直接访问订单属性

laravel 中的 OrderBy json 列

在全局安装 Composer 包后运行命令

一个php应用程序可以实例化多个RNG吗

如何将在同一台服务器上运行的 2 个 PHP 应用程序与使用公共会话分开