代码之家  ›  专栏  ›  技术社区  ›  Mooseman

如果不是从include〔closed〕运行,则运行代码

php
  •  2
  • Mooseman  · 技术社区  · 13 年前

    第1.php页:

    include 'page2.php';
    echo $info;
    

    第2页php:

    $info = "some info";
    if(!included){
      echo 'Why are you on this page?';
    }
    

    的目标 if(!included){ 是为了确定 page2.php 通过加载 include 在里面 page1.php ,或者如果用户直接请求了该页面。文档中没有返回此类值的函数。如何创建这样的函数?

    3 回复  |  直到 11 年前
        1
  •  5
  •   bwoebi    13 年前

    基本上有两种选择:

    a) 与核对 debug_backtrace 如果你也包括在内

    $bt = end(debug_backtrace()); // supposing that you don't include in functions / from other included files etc...
    if (!empty($bt) && in_array($bt["function"], array("include", "include_once", "require", "require_once"))) {
        // you're being included!
    }
    

    b) 在page1.php中定义一些常量、变量等,并检查page2.php(如果存在)( defined isset )

        2
  •  1
  •   Your Common Sense    13 年前
    if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) {
       echo "wild and free!";
    }
    
        3
  •  1
  •   Codeacula    13 年前

    窃取/同意bwoebi,你可以做出定义。

    在page1.php中:

    define("PAGE1_NOT_USER", true);
    

    在page2.php中,对于只想在用户请求时运行的代码:

    if(!defined("PAGE1_NOT_USER"))
    {
        <code here>
    }
    

    我的PHP已经生疏了,但这应该可以解决问题。debug选项涵盖了所有基础:Mine只涵盖了这一点(以及您可能使用define的其他任何地方)。

    推荐文章