Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set_include_path() not working with relative require()

Tags:

php

I am "requiring" a file that has a require() call of its own. But calling set_include_path() is not working with a relative path in require(). Unfortunately I have no control over the code file being required.

C:/myapp/index.php - My code

set_include_path(get_include_path() . ';C:/app/subfolder');
require('C:/app/subfolder/index.php');

C:/app/subfolder/index.php - Third party code (no control)

require('../config.php'); // Require file located at C:/app/config.php

The result:

Failed opening required '../config.php' (include_path='.;C:/app/subfolder')

This does not work, even though C:/app/subfolder is in the include path. I would expect ../config.php to be C:/app/subfolder/../config.php. Perhaps I am not doing it correctly.

In this case C:/app/subfolder/index.php was originally never meant to be included into another PHP file. However, I am building code in front of it, and I want C:/app/subfolder/index.php to still be able to require/include files as if it never left its location.

I have read that using dirname() or __DIR__ fixes the relative path issue in require(), but I cannot change the code in C:/app/subfolder/index.php.

Is there a way to make this work?

like image 340
Joe Avatar asked Sep 25 '22 03:09

Joe


1 Answers

Your problem as nothing to do with set_include_path() scope. Your fatal error shows actual include_path too, in which you can see your added path.

The problem is that the ../ call doesn't look at include_path, but at current working directory. This can be hard to understand calling the script via HTTP URL, but is more clear if you can call the script via commandline.

If you write this script at /usr/angelina/myproject/subfolder/index.php (note: in this explanatory example I will use Unix filePath/commands):

set_include_path( '/usr/angelina/myproject/subfolder' );
require( '../config.php' );

Then, in terminal, you write:

cd /usr/angelina/myproject/subfolder
php index.php

the script will be executed fine. But if you write:

cd /usr/angelina/myproject
php subfolder/index.php

the script will fails, even if include path is set inside the same script you call.

Above example to explain that your problem is not the include path, but the current working directory. To solve your issue, you have to change current directory with chdir().

So, in C:/myapp/index.php you have to write:

chdir( 'C:/app/subfolder' );
require( 'C:/app/subfolder/index.php' );

And your script will works (or, at least: on my side it worked...)

like image 96
fusion3k Avatar answered Nov 15 '22 12:11

fusion3k