Prevent direct access to a php include file

2018-12-31 10:19发布

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?

30条回答
流年柔荑漫光年
2楼-- · 2018-12-31 10:27

The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.

I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.

查看更多
刘海飞了
3楼-- · 2018-12-31 10:28

The easiest way is to set some variable in the file that calls include, such as

$including = true;

Then in the file that's being included, check for the variable

if (!$including) exit("direct access not permitted");
查看更多
牵手、夕阳
4楼-- · 2018-12-31 10:31

You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript. You can place this code in the Body section of your HTML code, so the error shows there.

<?
if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
else { ?>

Place your other HTML code here

<? } ?>

End it like this, so the output of the error will always show within the body section, if that's how you want it to be.

查看更多
若你有天会懂
5楼-- · 2018-12-31 10:32

The following code is used in the Flatnux CMS (http://flatnux.altervista.org):

if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) )
{
    header("Location: ../../index.php");
    die("...");
}
查看更多
人气声优
6楼-- · 2018-12-31 10:32

Do something like:

<?php
if ($_SERVER['SCRIPT_FILENAME'] == '<path to php include file>') {
    header('HTTP/1.0 403 Forbidden');
    exit('Forbidden');
}
?>
查看更多
低头抚发
7楼-- · 2018-12-31 10:35

An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file

<FilesMatch "\.(inc)$">
    Order deny,allow
    Deny from all
</FilesMatch>
查看更多
登录 后发表回答