在其他人打开之前保护要包含的PHP文件

I'm working on a small PHP Project. I want to include many PHP files, but I want to protect them before opening via directlink by other people.

For example:

<?php include 'content/scripts/php/sample.php'; ?>

I don't want people to access the sample.php via

http://samplepage.com/content/scripts/php/sample.php

If you are in a shared hosting and can't place files outside the web server folder or can't use .htaccess a common method is to define a constant in your main php file and then check for that constant at the top of each included file and die() if not defined. In this way people can still access the file with its path but they will see only a blank page. Wordpress uses this approach for example.

in your main php file:

define('APP', true);

in the included files:

if(!defined('APP')) die();

Just place them outside your web server public folder (and maybe play a bit with set_include_path for easier access to them from your public php files).

Also you could solve this in PHP itself, like this:

index.php

<?php

define('PARENT_AVAILABLE', true);

include.php

<?php

if (!defined('PARENT_AVAILABLE')) die('Not allowed');