Reputation: 1889
How can I code a php file to execute only if the file is included. For example in this form it won't run (or will be redirected to another page):
www.example.com/file.php
And in this form it will run:
<?php
include 'file.php';
?>
Is that possible?
Upvotes: 1
Views: 739
Reputation: 481
You can define constant in main file and check it in included file.
index.php
<?php
define('IN_INDEX', true);
include __DIR__ . '/included.php';
included.php
<?php
if (!defined('IN_INDEX')) {
redirect();
}
Upvotes: 2
Reputation: 155015
Add a guard expression to the start of the included file, so if you have these two files:
<?php
$runningFileName = "index.php";
include("included.php");
?>
<?php
if( empty( $runningFileName ) ) die("Cannot access this page directly");
?>
Upvotes: 2