Skip to content
Advertisement

require() reports that no such directory exists, but file_exists returns true on the exact same path

I have a very simple PHP file that is part of a unit test with PHPUnit, and I am getting an issue where require() reports back that it is unable to open the stream because no such file exists, but yet, on the next line tests if the file_exists and this returns true?

<?php
$inc1 = $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
require $inc1;
if (file_exists($inc1)){
    echo "yes";
}else
{
    echo "no";
}

What could be causing this behavior and for this to not work?

The exact error being returned by the console is:

Warning: require(/vendor/autoload.php): failed to open stream: No such file or directory in /Users/REDACTED/Documents/Github/XXX/tests/inc/emailSendTest.php on line 3

Fatal error: require(): Failed opening required '/vendor/autoload.php' (include_path='.:') in /Users/REDACTED/Documents/Github/XXX/tests/inc/emailSendTest.php on line 3

Advertisement

Answer

By referring to many other StackOverflow questions, I have found that this is a common problem with the way that PHPUnit treats directories and the solution to my problem is to use:

$envConfigInclude = realpath(dirname(dirname(__FILE__))) .  '/inc/env-config.php';

To include the file, this is because it will return the full proper path, and this is something that PHPUnit can interpret and return the correct include and the rest of the script will execute.

This answer is based on the findings of these two StackOverflow questions: PHPUnit doesn’t allow me to include files and Get parent directory of running script

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement