5

我有一个 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,您将.. 我将如何执行此操作..?如果可能的话..

4

5 回答 5

9

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

if (basename(__FILE__) != basename($_SERVER['SCRIPT_FILENAME'])) {
   //this is included
}
于 2012-12-12T19:29:11.197 回答
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";
}
于 2012-12-12T19:29:23.790 回答
1

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

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

于 2012-12-12T19:30:13.197 回答
1

“我想要它,这样人们就可以使用 include 'foo.php'.. 这是一个类,我不希望他们使用比他们更多的代码.. 我想要大部分代码上课。”

既然你需要这个,我会推荐你​​ class_exists 函数。 http://php.net/manual/en/function.class-exists.php

这样您就可以检查您的类是否已定义,无需检查文件是否包含在内。因为,如果它被定义,它的文件肯定被包含在内。

于 2012-12-12T19:33:27.557 回答
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);
于 2012-12-12T19:35:03.510 回答