kalaba2003
kalaba2003

Reputation: 1229

How can I prevent "include files" from being seen by users?

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?

Upvotes: 1

Views: 420

Answers (3)

adrien
adrien

Reputation: 4439

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();
}
...

Upvotes: 2

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

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

Upvotes: 7

Quentin
Quentin

Reputation: 943591

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.

Upvotes: 9

Related Questions