tags:

views:

169

answers:

3

Is it better to check for a defined constant, check the url, or any other ways....

something like

if(!defined(INCLUDED))

of

if($_SERVER['REQUEST_URI'] == $_SERVER['PHP_SELF'])

What ways do you check if a file was accessed directly..also, is it important to prevent direct access to pages... (I figure a site should work in the way it was designed, so accessing directly would go against that, but) what are your thoughts

A: 

Defining a constant is probably the best way to go about it, without delving into tons of code... Just define a constant before your include line, and check to see if it's defined in the included file...

main file

<?php
define("IS_INCLUDED",true);
include "included_file.php";
?>

included_file.php

<?php
if(!defined("IS_INCLUDED")){
header("Location: error_page.php");
}
?>

That way if they access the page, the constant won't be defined and they'll be redirected to wherever you want them to be.

BraedenP
+6  A: 

If you don't want them to be able to be accessed directly, you don't need to hack up your files. Just place them in a directory outside the publicly viewable directory, and they can't be accessed by the public. Your PHP scripts will still be able to access them easily.

Josh Leitzel
Another point, if you can't place the files outside the web directory, protect a directory using .htaccess and put them in there.
MitMaro
+4  A: 

There are three approaches to this problem that I commonly see/use:

  1. If the file isn't mean to be loaded directly via a URL, put it in an included directory (defined in php.ini) rather than under the document root;
  2. If you can't do (1) create one or more directories like 'include' under your document root and restrict access to them with mod_rewrite; or
  3. I tend to find that any file of mine that is included consists of nothing but functions anyway so it doesn't matter if someone accesses it directly or not.

As an example of (2):

RewriteEngine On
RewriteRule ^include/ [R=404,L]

This sends a file not found error to any attempts to hit the include directory.

cletus