hi im trying to make parts for the website i want to build and it's will be like: header.php, footer.php, etc... I want these files to work only when i include it and no one can directly access them. is there any way to do that please?
3 Answers
Here are two options you could give a try:
<?php
/**
* Returns true if current file is included
*/
function isIncluded() {
$f = get_included_files();
return $f[0] != __FILE__;
}
if(!isIncluded()) {
// Do some stuff, eg: print some HTML
} else {
// Show 403/error
}
?>
<?php
// You can also use (recommended)
if(__FILE__ !== $_SERVER["SCRIPT_FILENAME"]) {
// this file is being included
}
?>
You may also opt to put the files into a directory protected by a .htaccess
and a Deny from all
since PHP can bypass that, but users cannot.

- 297
- 1
- 12
It's a common and best practice to not have these scripts in your web root at all. You can put your includes in a directory elsewhere.
That is, you might have directories like this:
/www
index.php
/includes
header.php
footer.php
In your index.php
, you can always do require_once('../header.php');
This is better than configuring your web server to disallow access. If you use a .htaccess
file as suggested by others, it's possible for that config to get lost, moved, ignored by the proper config files outside of the webroot, etc. You wouldn't want to accidentally reveal those files.

- 159,648
- 54
- 349
- 530
You can create a .htaccess file and place it in the independent directory (eg. "common") which cannot be executed directly. This .htaccess file should contain the following directives:
order deny,allow
deny from all

- 253
- 2
- 9