仅显示不包括在内?

时间:2012-12-12 19:26:20

标签: php include

我有一个PHP脚本,我希望它只会在您浏览器中查看该页面时显示此特定文本,并且它不包含在其他脚本中..

例如

//foo.php
<?php
   if(!included){
      echo "You can only see this if this is the page you're viewing";
   }
?>

//bar.php
<?php
  include 'foo.php';
?>

现在,当你查看“bar.php”时,你不应该看到文字..但是如果你打开foo.php,你会......我怎么会这样做...?如果可能的话..

5 个答案:

答案 0 :(得分:9)

本身不可能,但如果您在网站上公开php页面,例如example.com/bar.php,如果您使用的是apache,则可以查看$_SERVER['SCRIPT_FILENAME']

if (basename(__FILE__) != basename($_SERVER['SCRIPT_FILENAME'])) {
   //this is included
}

答案 1 :(得分:3)

在bar.php中:

<?php
    $included = true;
    include 'foo.php';
?>

在foo.php中:

if(!isset($included)){
      echo "You can only see this if this is the page you're viewing";
}

答案 2 :(得分:1)

您应该看到array get_included_files(void) http://php.net/manual/en/function.get-included-files.php

它为您提供了所包含文件的列表。

答案 3 :(得分:1)

“我想要它以便人们可以使用include'foo.php'..这是一个类,我不希望他们必须使用比他们更多的代码..我希望大多数代码中的代码。“

因为你需要这个,我建议你使用class_exists函数。 http://php.net/manual/en/function.class-exists.php

通过这种方式,您可以检查您的类是否已定义,无需检查是否包含文件。因为,如果已经定义,那么肯定会包含它的文件。

答案 4 :(得分:0)

使用include_once()或require_once()函数始终是一个好习惯。这样您就可以确保文件只包含一次。

在您包含的页面中定义一个常量:

 if(defined("ALREADY_LOADED")) {
     echo "this page was loaded already";
     die("ciao");
 }
  else {
     define("ALREADY_LOADED", 1);
 }

现在,只要你需要这个控件,只需在加载文件之前定义:

 define("ALREADY_LOADED", 1);
相关问题