Andrew
Andrew

Reputation: 2851

Allow php file only to be executed when included by another PHP file

What is the correct to allow a PHP file only to be executed if it is included in another PHP file?

For example, let's say I have my main application file "main.php". This file includes "settings.php" as such:

// www.mydomain.com/MAIN.PHP
<?php
require 'settings.php';
?>

// www.mydomain.com/SETTINGS.PHP
<?php
// DO SOMETHING
?>

How can I precent "settings.php" from being executed if a user runs "www.mydomain.com/SETTINGS.PHP" from their browser?

I'm looking for a PHP-Only solution.

Upvotes: 2

Views: 2869

Answers (5)

AbraCadaver
AbraCadaver

Reputation: 78994

The first solution is obviously to not put it in a web accessible location. Sometimes this isn't feasible, so you can make a check:

// www.mydomain.com/MAIN.PHP
<?php
define('SOMETHING', true);
require 'settings.php';


// www.mydomain.com/SETTINGS.PHP
<?php
if(!defined('SOMETHING')) { die(); }
// DO SOMETHING

Or you can use something similar to this in a global header include:

if(strpos($_SERVER["PHP_SELF"], basename(__FILE__) !== false) { die(); }

Upvotes: 5

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

Another method is to check if the requested file (usually $_SERVER['REQUEST_FILENAME']) matches __FILE__. __FILE__ is set to the name of the file you are currently in, even if in an include. If they are the same, then you are loading a file directly. If different, it can be assumed as included.

Upvotes: 0

Bob Brown
Bob Brown

Reputation: 1502

One way is to check for a "magic" value that is set when you include settings.php.

// www.mydomain.com/MAIN.PHP
<?php
$magic = "c00f0c4675b91fb8b918e4079a0b1bac";
require 'settings.php';
?>

// www.mydomain.com/SETTINGS.PHP
<?php
if ($magic != "c00f0c4675b91fb8b918e4079a0b1bac") {
    die("Cannot be executed independently.");
}
// DO SOMETHING
?>

This protects against casual fooling around; it will not protect you from someone who can read your PHP files, i.e. someone who has access to your server.

Upvotes: 2

Jonan
Jonan

Reputation: 2536

In settings.php, you can check if the $_SERVER['SCRIPT_FILENAME'] is settings.php; if it is: the script is being accessed directly, if not: the script is being included

//settings.php
echo $_SERVER['SCRIPT_FILENAME']; // echoes 'settings.php'

//file.php
include 'settings.php'; //echoes 'file.php';

This means you can do something like this:

//settings.php
if($_SERVER['SCRIPT_FILENAME'] != 'path/to/the/settings/file/settings.php'){
    define('SETTING', true);
}

Upvotes: 1

user2549271
user2549271

Reputation: 1

If you want to allow include of remote files, the directive allow_url_include must be set to On in php.ini

See reference

Upvotes: 0

Related Questions