Normalize/Standard path root to CLI/WEB

122 Views Asked by At

I have this short script to detect the user usage environment and try to normalize the root path:

Located in C:\xampp\htdocs\dev\t2\Last-Hammer\configs\const\loader.php

$env= '';
if (php_sapi_name() == 'cli') {
    $env= 'cli';
    if (!isset($_SERVER['PWD'])) {
        $path = dirname(__DIR__).'\\';
    } else {
        $path = dirname($_SERVER['PWD']);
    }
} else {
    $env= 'web';
    $path = $_SERVER['DOCUMENT_ROOT'];
}
echo $path;
echo PHP_EOL;
echo $env;
file_get_contents($path.'configs/const/client.xml')

i use it from 2 diferent files: index.php that wor well in root folder but trying to use it from a sub-directory like this /dev/cron.php

cron.php content:

$path = (!isset($_SERVER["PWD"]) ? dirname(__DIR__).'\\' : dirname($_SERVER["PWD"]));
require_once $path.'/configs/const/loader.php';

i get this output

//from Web environment 
C:/xampp/htdocs/dev/t2/Last-Hammer/ 
web

and

//from CLI environment 
C:\xampp\htdocs\dev\t2\Last-Hammer 
cli

the problem is that this work correctly from Web environment but not work correctly in CLI, when i try to execute like: php cron.php code try to make a file_get_contents... like this using cli get this error:

PHP Warning: file_get_contents(C:\xampp\htdocs\dev\t2\Last-Hammer\configs\configs/const/client.xml): failed to open stream: No such file or directory in C:\xampp\htdocs\dev\t2\Last-Hammer\configs\const\loader.php on line 24

Warning: file_get_contents(C:\xampp\htdocs\dev\t2\Last-Hammer\configs\configs/const/client.xml): failed to open stream: No such file or directory in C:\xampp\htdocs\dev\t2\Last-Hammer\configs\const\loader.php on line 24

what is expected is that both for CLI or WEB, the root of the project is similar to: C:/xampp/htdocs/dev/t2/Last-Hammer/ and does not change constantly in the case of CLI depending on where it is executed the php file, as root could set in CLI. regardless of where it runs.

2

There are 2 best solutions below

2
AudioBubble On

You are lacking trailing "\" on cli case. to uniform both, you could use str_replace():

$env= '';
if (php_sapi_name() == 'cli') {
    $env= 'cli';
    if (!isset($_SERVER['PWD'])) {
        $path = dirname(__DIR__).'\\';
    } else {
        $path = dirname($_SERVER['PWD']).'\\';
    }
} else {
    $env= 'web';
    $path = $_SERVER['DOCUMENT_ROOT'];
}
$path = str_replace( '\\', '/', $path );
echo $path;
echo PHP_EOL;
echo $env;
file_get_contents($path.'configs/const/client.xml')
8
SirPilan On

define in your main scripts:

define('DOCROOT', '../'); // this in your cron.php
define('DOCROOT', './'); // this in your index.php

Just use relative paths:

$path = DOCROOT;
file_get_contents($path.'configs/const/client.xml')