Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查是否包含或加载了文件_Php - Fatal编程技术网

Php 检查是否包含或加载了文件

Php 检查是否包含或加载了文件,php,Php,使用include/include\u once/require/require\u once检查文件是否包括在内,或者是否直接加载了页面,有什么优雅的方法吗?在创建类文件时,我试图在类文件中设置一个测试文件 我正在寻找类似于Python的if uuuu name\uuuuu==“\uuuuu main\uuuuu”:技术。无需设置全局变量或常量。您可以通过返回包含或必需文件名称的数组来执行此操作,并根据\uuuu文件\uuuu进行验证,它们无法将它们分开为包含/包含一次/require/req

使用
include
/
include\u once
/
require
/
require\u once
检查文件是否包括在内,或者是否直接加载了页面,有什么优雅的方法吗?在创建类文件时,我试图在类文件中设置一个测试文件


我正在寻找类似于Python的
if uuuu name\uuuuu==“\uuuuu main\uuuuu”:
技术。无需设置全局变量或常量。

您可以通过返回包含或必需文件名称的数组来执行此操作,并根据
\uuuu文件\uuuu
进行验证,它们无法将它们分开为
包含/包含一次/require/require\u一次
,但php有
获取包含的文件
获取必需的文件
它是相同的,只返回所有包含文件的数组。如果它的
必需
包含
,则它不会将其分开

示例
a.php

include 'b.php';
include_once 'c.php';
require 'd.php';
var_dump(get_required_files());
输出

array
  0 => string '..\lab\stockoverflow\a.php' (length=46) <---- Returns current file
  1 => string '..\lab\stockoverflow\b.php' (length=46)
  2 => string '..\lab\stockoverflow\c.php' (length=46)
  3 => string '..\lab\stockoverflow\d.php' (length=46)
使用的类

class IncludeManager {
    private $list = array();
    private $tokens = array();
    private $find;
    private $file;
    private $type = array(262 => "include",261 => "include_once",259 => "reguire",258 => "require_once");

    function __construct($file) {
        $this->file = $file;
        $this->_parse();
    }

    private function _parse() {
        $tokens = token_get_all(file_get_contents($this->file));
        for($i = 0; $i < count($tokens); $i ++) {
            if (count($tokens[$i]) == 3) {
                if (array_key_exists($tokens[$i][0], $this->type)) {
                    $f = $tokens[$i + 1][0] == 371 ? $tokens[$i + 2][1] : $tokens[$i + 1][1];
                    $this->list[] = array("pos" => $i,"type" => $this->type[$tokens[$i][0]],"file" => trim($f, "\"\'"));
                }
            }
        }
    }

    public function find($find) {
        $finds = array_filter($this->list, function ($v) use($find) {
            return $v['file'] == $find;
        });

        return empty($finds) ? false : $finds;
    }

    public function getList() {
        return $this->list;
    }

    public function getFiles($type = null) {
        $finds = array_filter($this->list, function ($v) use($type) {
            return is_null($type) ? true : $type == $v['type'];
        });
        return empty($finds) ? false : $finds;
    }
}
类IncludeManager{
private$list=array();
私有$tokens=array();
私人$find;
私人$file;
private$type=array(262=>“include”,261=>“include_once”,259=>“reguire”,258=>“require_once”);
函数构造($file){
$this->file=$file;
$this->_parse();
}
私有函数_parse(){
$tokens=token_get_all(file_get_contents($this->file));
对于($i=0;$itype)){
$f=$tokens[$i+1][0]==371?$tokens[$i+2][1]:$tokens[$i+1][1];
$this->list[]=array(“pos”=>$i,“type”=>$this->type[$tokens[$i][0],“file”=>trim($f,“\”\”);
}
}
}
}
公共函数find($find){
$finds=array\u filter($this->list,function($v)use($find){
返回$v['file']==$find;
});
返回空($finds)?false:$finds;
}
公共函数getList(){
返回$this->list;
}
公共函数getFiles($type=null){
$finds=array\u filter($this->list,function($v)use($type){
返回值为空($type)?真:$type==$v['type'];
});
返回空($finds)?false:$finds;
}
}
引自:

我一直在寻找一种方法来确定一个文件是否被包含或直接调用,所有这些都是从文件中获取的。在我的探索过程中的某个时候,我通过了这个线程。通过检查这个和其他网站上的各种线程以及PHP手册中的页面,我得到了启发,并产生了以下代码:

本质上,它比较当前文件的名称( 可以包含)与正在执行的文件相同


信用:@Interwebs Cowboy

我很感激所有的答案,但我不想在这里使用任何人的解决方案,所以我结合了您的想法,得到了以下结果:

<?php
    // place this at the top of the file
    if (count(get_included_files()) == 1) define ('TEST_SUITE', __FILE__);

    // now I can even include bootstrap which will include other
    // files with similar setups
    require_once '../bootstrap.php'

    // code ...
    class Bar {
        ...
    }
    // code ...

    if (defined('TEST_SUITE') && TEST_SUITE == __FILE__) {
        // run test suite here  
    }
?>

我不认为
获取包含的\u文件是完美的解决方案,如果在检查之前您的主脚本包含了一些其他脚本呢?我的建议是检查
\u文件\u
是否等于
realpath($argv[1])

<?php
require('phpunit/Autoload.php');

class MyTests extends PHPUnit_Framework_TestCase
{
    // blabla...
}

if (__FILE__ == realpath($argv[0])) {
    // run tests.
}

注意:在WAMP服务器上,虚拟主机有时会继承默认的文档根设置,导致
$\u服务器['document\u root']
显示错误的路径

<?php
    if (__FILE__ == $_SERVER['SCRIPT_FILENAME'])
    {
        //file was navigated to directly
    }
?>
据我所知,这太简单了。。 我做过这样的事情:

//code for file.php
if (!isset($file_included)){
   echo "It was loaded!";
} else {
  echo "It was included!";
}

//code for loader.php
//proves that atleast loader.php has loaded,
//not the file we targeted first..
$file_included = true;
include("../file.php");

就是这样..和python一样简单。

我在浏览这个问题时采用了类似的方法。我找到的解决方案是根据需要在include_once方法中加载每个文件。希望这有帮助

$FILES = get_included_files();  // Retrieves files included as array($FILE)
$FILE = __FILE__;               // Set value of current file with absolute path
if(!in_array($FILE, $FILES)){   // Checks if file $FILE is in $FILES
  include_once "PATH_TO_FILE";  // Includes file with include_once if $FILE is not found.
}
我建立了以下功能来检查加载的文件:

ARRAY_DUMP($FILES);

function ARRAY_DUMP($array){
  echo "
    <span style='font-size:12px;'>".date('h:i:s').":</span>
    <pre style='font-size:12px;'>", print_r($array, 1), "</pre>
  ";
}
get_included_files()
返回数组,其中0索引表示第一个“包含”文件。因为直接运行在这个术语中表示“包含”,所以您可以简单地检查
uu文件的第一个索引是否相等:

if(get_included_files()[0] == __FILE__){
    do_stuff();
}
这在PHP4上不起作用,因为PHP4没有在这个数组中添加运行文件。

这里有一个不同的想法。 只要在需要时包含该文件即可。 在包含文件中,您可以决定是否需要包含以下内容:

<?php
if (defined("SOME_UNIQUE_IDENTIFIER_FOR_THIS_FILE"))
    return;
define("SOME_UNIQUE_IDENTIFIER_FOR_THIS_FILE", 1);

// Rest of code goes here
工作解决方案:

我该如何对照我加载的内容检查它呢?
/test.php
可以包含
/includes/test.php
这里的完整示例:对我不起作用。正如关于get_includes_文件的文档所述:最初调用的脚本被视为“包含文件”,“因此,它将与include和family引用的文件一起列出。想想看,我们找到了一种方法。。。。这个问题的副本有点模棱两可。如果您想知道是否已经加载了不同的文件(与当前文件不同):
if(在_数组(uu DIR_u./path/to/file.php',get_included_files()){echo_uudir_u.'/path/to/file.php已经加载了';
我认为当两个文件名称相同但位于不同的目录中时,这种情况就会中断。无需
basename()
即可正常工作。例如,如果
/var/www/index.php
包括
/var/www/test/index.php
/var/www/test/index.php
会认为它是直接调用的。尽管如此,+1,因为这对我帮助很大:)当文件被cron作业调用时,它不起作用,因为您没有$\u服务器变量…只是否决了它,因为NullPoièteè的答案更好,应该被IMO接受。虽然这可以解决问题,但不鼓励只使用代码的答案。最好留下一个解释,说明为什么这会解决问题。请参阅。您的答案应该解释这是如何解决问题的,以及这如何改进现有的投票结果相同的答案。另外,由于这个问题已经5年了,并且有很多被高估的答案,你的努力会得到最近有未回答问题的用户的赞赏
$FILES = get_included_files();  // Retrieves files included as array($FILE)
$FILE = __FILE__;               // Set value of current file with absolute path
if(!in_array($FILE, $FILES)){   // Checks if file $FILE is in $FILES
  include_once "PATH_TO_FILE";  // Includes file with include_once if $FILE is not found.
}
ARRAY_DUMP($FILES);

function ARRAY_DUMP($array){
  echo "
    <span style='font-size:12px;'>".date('h:i:s').":</span>
    <pre style='font-size:12px;'>", print_r($array, 1), "</pre>
  ";
}
currentArray
(
  [0] => /home/MY_DOMAIN/hardeen/index.php
  [1] => /home/MY_DOMAIN/hardeen/core/construct.php
  [2] => /home/MY_DOMAIN/hardeen/core/template.php
  [3] => /home/MY_DOMAIN/hardeen/bin/tags.php
  [4] => /home/MY_DOMAIN/hardeen/bin/systemFunction.php
)
if(get_included_files()[0] == __FILE__){
    do_stuff();
}
<?php
if (defined("SOME_UNIQUE_IDENTIFIER_FOR_THIS_FILE"))
    return;
define("SOME_UNIQUE_IDENTIFIER_FOR_THIS_FILE", 1);

// Rest of code goes here
$target_file = '/home/path/folder/file.php'; // or use __FILE__

if ($x=function($e){return str_replace(array('\\'), '/', $e);}) if(in_array( $x($target_file), array_map( $x ,  get_included_files() ) ) )
{
    exit("Hello, already included !");
}