DOCUMENT_ROOT not available

I would like to access to a file located in the same folder as the exe file. The purpose of the cli-application is to read and convert text files.

I tried to use several possibilities, also mentioned in the documentation:

  • use of DOCUMENT_ROOT path
  • read the path of the exe file -> dirname of PHP_SELF
  • absolute definition of the path

I cannot access to the placed files within the folder of the exe. These text files will change regularly, so they cannot be packed within the application.

Been a little while since used, but pretty sure this is what works for me:

include $_SERVER['DOCUMENT_ROOT'].'/folder/subfolder/example.txt';

Should work for writing too if your setup for that correctly.

Yes, I tried the same before writing my post - but DOCUMENT ROOT is empty

Some technical data:

  • CLI application
  • PHP 7.1
  • default php settings
  • NOT used absolute path

Maybe because cli-application is different. Will stand down and let the pros help. Sorry I could not…

$_SERVER[‘DOCUMENT_ROOT’] is empty because a cli application isn’t running on a server and it is not processing an HTTP request.

To get the full path to the EXE dir, use this code:

For instance, print (dirname(__DIR__));

Dear everyone,

I would like to share the solution that works. Maybe any one other has the same situation:

$strDirectory = (dir name(__ DIR__));
$resDir = open dir($strDirectory);
while($strFile = read dir($resDir)){
print “\r\n”.$strFile.": ";
$strContent = file _get _contents($strDirectory.DIRECTORY_SEPARATOR.$strFile);
print sub str($strContent, 0, 50);

PS: I had to enter some additional spaces because the forum software said forbidden of the original version


It will be usefull to add :

if(is_dir( $strDirectory))

to verify that it is a directory and it exists .

$strDirectory = (dirname(__DIR__));
$resDir = opendir($strDirectory);
while($strFile = readdir($resDir)){
print "\r\n".$strFile.": ";
$strContent = file_get_contents($strDirectory.DIRECTORY_SEPARATOR.$strFile);
print substr($strContent, 0, 50);

1 Like