简体   繁体   中英

How get nested, relative includes to work?

I am using a 3rd party php library ( phpseclib ) that has files which include other files. 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!

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:

require_once('File/ASN1.php');

I know this occurs because once I include x509.php into my script, the code is executed there. Without changing the PHP code in the included library, is there any way to make this work? To make the include use a path relative to where I installed it?

EXAMPLE:

Assume a file structure:

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

myscript.php

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

x509.php

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

asn1.php

<?php echo "included"; ?>

Use the chdir to change the current working directory. I would also advise using getcwd to get the working directory before you do this then changing back to that directory when done.

$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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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