1

My site's main file(index.php) code is here:

<?php include 'header.php'; include 'sidebar.php'; include 'content.php'; include 'footer.php'; ?> 

But I don't want any user to see these include files by writing "www.domain.com/header.php". Should i insert a php code in these files or is that possible?

3 Answers 3

9

You have several options.

  1. Keep the files outside the webroot (so they don't automatically get URIs of their own)
  2. Configure your webserver so it refuses to serve them
  3. Test if a variable/constant is set, and then set it in every one of the files that is allowed to include them. exit if it is not set.
Sign up to request clarification or add additional context in comments.

Comments

7

Here's a PHP for you.

if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){exit();} 

In short, this quits execution if the calling file is itself.

Source: http://thephpcode.blogspot.se/2009/07/creating-include-only-php-files.html

1 Comment

Nice work, man. It is a perfect answer, in my opinion. Sometimes it is not possible(maybe difficult) to apply variables or constants to included files because they are called via AJAX
2

You can define a constant in your main file, and use it in your included files to detec wether they were really included or not:

index.php

<?php define('REALLY_INCLUDED', true); include'header.php'; 

header.php

<?php if(!defined('REALLY_INCLUDED') || !REALLY_INCLUDED) { exit(); } ... 

3 Comments

... and then you forget the constant somewhere and expose the file. "oops". if you want something kept private, don't put it into the document root in the first place.
This will throw some unnecessary warnings. Add quotes during definition: define('REALLY_INCLUDED', true); and use the correct function to check if the constant is defined: if(!defined('REALLY_INCLUDED') || !REALLY_INCLUDED) { ...
What if there is an included file that is called in another included file? And the first one is called by Javascript? The first one cannot define the constant and check if the constant has been set at the same time. It won’t work. I suggest @AndreasEriksson ‘s answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.