简体   繁体   English

如何嵌套,相对包含工作?

[英]How get nested, relative includes to work?

I am using a 3rd party php library ( phpseclib ) that has files which include other files. 我正在使用具有包含其他文件的文件的第三方php库( phpseclib )。 It only seems to work when I have it installed in the "root" of whatever directory I'm including the first file from. 仅当我将其安装在我要包含的第一个文件的任何目录的“根目录”中时,它才似乎起作用。 If I put it in a sub-folder, the includes in the phpseclib files become unable to find the other files, despite them being relative! 如果我将其放在子文件夹中,则尽管phpseclib文件是相对的,但它们仍然找不到其他文件!

This works (installed it directly in my folder): 这有效(将其直接安装在我的文件夹中):

include( "File/X509.php" );

This does not work (installed it in a sub-folder in my folder): 不起作用 (安装它的子文件夹我的文件夹中):

include( "phpseclib/File/X509.php" );

What fails is X509.php's call to include a file: 失败的是X509.php包含文件的调用:

require_once('File/ASN1.php');

I know this occurs because once I include x509.php into my script, the code is executed there. 我知道会发生这种情况,因为一旦将x509.php包含到脚本中,代码就会在该脚本中执行。 Without changing the PHP code in the included library, is there any way to make this work? 在不更改包含的库中的PHP代码的情况下,有什么方法可以使此工作正常进行? To make the include use a path relative to where I installed it? 要使include使用相对于我安装位置的路径?

EXAMPLE: 例:

Assume a file structure: 假设一个文件结构:

/myfolder/myscript.php
/myfolder/sub/file/x509.php
/myfolder/sub/file/asn1.php

myscript.php myscript.php

<?php include( "sub/file/x509.php" ); ?>

x509.php x509.php

<?php include( "file/asn1.php" ); ?>

asn1.php asn1.php

<?php echo "included"; ?>

Use the chdir to change the current working directory. 使用chdir更改当前工作目录。 I would also advise using getcwd to get the working directory before you do this then changing back to that directory when done. 我还建议在执行此操作之前,先使用getcwd获取工作目录,然后在完成后更改回该目录。

$cwd = getcwd();
chdir("phpseclib/");
include("File/X509.php");
chdir($cwd);

I just need to add the path like this (and then reset it after): 我只需要添加这样的路径(然后在之后将其重置):

//This is so we don't screw up anything else in the PHP web app
$currentIncludePath = get_include_path();

//Need to let phpseclib know where to find its files
set_include_path( "phpseclib" . PATH_SEPARATOR . $currentIncludePath );

//Now include the file(s)
include( "phpseclib/File/X509.php" );

//Now set back to normal
set_include_path( $currentIncludePath );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM