1

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?

Imri Persiado
  • 1,857
  • 8
  • 29
  • 45
  • http://stackoverflow.com/questions/12999658/check-if-a-file-was-included-orloaded – Henk Jansen Dec 12 '13 at 08:23
  • Are you possibly looking for the solution to *store non-public files outside of the public webroot* so they can't be directly accessed by users? – deceze Dec 12 '13 at 08:23
  • Create flag ( as constant ) and check if `defined` – u_mulder Dec 12 '13 at 08:24
  • I didn't get the sense of "execute only if included" (if it's included as PHP file, it will be executed) - but remote files will be included as they will be processed with remote web-server. You can't get source code unless web-server treats PHP files as usual text files – Alma Do Dec 12 '13 at 08:24

2 Answers2

2

Add a guard expression to the start of the included file, so if you have these two files:

  1. included.php
  2. index.php

index.php

<?php
$runningFileName = "index.php"; 
include("included.php");
?>

included.php

<?php 
if( empty( $runningFileName ) ) die("Cannot access this page directly");
?>
Dai
  • 141,631
  • 28
  • 261
  • 374
2

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();
}
merkushin
  • 481
  • 9
  • 17