Prevent direct access to a php include file

Alterlife picture Alterlife · Jan 3, 2009 · Viewed 226.9k times · Source

I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.

Basically I need to do a check as follows in the php file:

if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");

Is there an easy way to do this?

Answer

UnkwnTech picture UnkwnTech · Jan 3, 2009

Add this to the page that you want to only be included

<?php
if(!defined('MyConst')) {
   die('Direct access not permitted');
}
?>

then on the pages that include it add

<?php
define('MyConst', TRUE);
?>