1
votes

I am trying to include a php file from the parent directory and I getting error:

admin@webby:~$ /usr/bin/php /var/phpscripts/email_parser/tests/_email-test.php PHP Fatal error: require_once(): Failed opening required '../PlancakeEmailParser.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/phpscripts/email_parser/tests/_email-test.php on line 6

Fatal error: require_once(): Failed opening required '../PlancakeEmailParser.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/phpscripts/email_parser/tests/_email-test.php on line 6

PHP file

#!/usr/bin/php
<?php
error_reporting(E_ALL ^ E_NOTICE ^E_WARNING);
ini_set("display_errors" , 1);

require_once("../PlancakeEmailParser.php");

// etc

?>

Folder Structure

admin@webby:/var/phpscripts/email_parser$ find .
.
./composer.json
./README.txt
./LICENSE.txt
./PlancakeEmailParser.php
./tests
./tests/_email-test.php

For testing it works fine when I move PlancakeEmailParser.php into the tests directory and remove the "../" from the require

2
Try doing it this way: require_once(__DIR__."/../PlancakeEmailParser.php");Get Off My Lawn
@hakre: how come relative include do not work when calling a php script from command lineJohn Magnolia
@JohnMagnolia: They work, but the question is to which base path are they relative too and which one is the current base path PHP uses to resolve them? (Working directory differs) - the other point is PHP's configuration for the include path directive. (php configuration differs) - That are merely the two points I can imagine. Provide the getcwd() and the value of the setting: var_dump(getcwd(), get_include_path()); to explain this better.hakre

2 Answers

5
votes

The line

require_once("../PlancakeEmailParser.php");

Is not using a fully qualified file-system path or PHP-URI-scheme. Therefore its outcome depends on PHP configuration, most often because of the include directory configuration.

The PHP CLI can use a different configuration file than with your webserver - or - the working directory is different as with your webserver (probably the later plays more of a role in your specific scenario).

What you want can be easily expressed fully qualified, too:

require_once(__DIR__ . "/../PlancakeEmailParser.php");

This is probably what you're looking for.

1
votes

Quote from PHP CLI SAPI: Differences to other SAPIs:

It does not change the working directory to that of the script. (-C and --no-chdir switches kept for compatibility)

In order to keep relative paths in your script working as-is, change directory to where the script resides, then execute the script:

cd /var/phpscripts/email_parser/tests/ && ./_email-test.php