Imri Persiado
Imri Persiado

Reputation: 1889

Executing a file only if it's included

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

Answers (2)

merkushin
merkushin

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

Dai
Dai

Reputation: 155015

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");
?>

Upvotes: 2

Related Questions