【问题标题】:Executing a file only if it's included仅在包含文件时才执行文件
【发布时间】:2013-12-12 08:22:03
【问题描述】:

我怎样才能编写一个 php 文件以仅在包含该文件时才执行。例如在这种形式下它不会运行(或将被重定向到另一个页面):

www.example.com/file.php

它会以这种形式运行:

<?php
include 'file.php';
?>

这可能吗?

【问题讨论】:

  • 您是否正在寻找解决方案来将非公共文件存储在公共 webroot 之外,以便用户无法直接访问它们?
  • 创建标志(作为常量)并检查是否defined
  • 我没有得到“仅在包含时执行”的感觉(如果它作为 PHP 文件包含,它将被执行) - 但远程文件将被包含,因为它们将使用远程 Web 处理-服务器。除非网络服务器将 PHP 文件视为普通文本文件,否则您无法获取源代码

标签: php


【解决方案1】:

在包含文件的开头添加一个保护表达式,所以如果你有这两个文件:

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

【讨论】:

    【解决方案2】:

    您可以在主文件中定义常量并在包含的文件中检查它。

    index.php

    <?php
    define('IN_INDEX', true);
    include __DIR__ . '/included.php';
    

    包含的.php

    <?php
    if (!defined('IN_INDEX')) {
        redirect();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 2015-09-09
      • 2018-09-15
      相关资源
      最近更新 更多