SatanicGeek SatanicGeek - 1 month ago 7
Bash Question

PHP : chdir('../') not working from command line

I'm developing a PHP cron script to check if a server is up or not (Ping).

Here is my code :

// Remonte d'un dossier
chdir('../');

// Inclusion du header pour avoir les infos de connexion à la db, fonctions, etc ...
require_once('./includes/header.php');

// Requête pour récupérer toutes les IP à pinger (Non-exclues donc)
$sReqGetAllServers = " SELECT
*
FROM
host
WHERE
exclude_machine = :exclude_machine";

// Préparation de la requête
$oDatabase->Prepare($sReqGetAllServers);

// On bind la valeur au paramètre dans le WHERE
$oDatabase->BindValue(':exclude_machine', 'n', PDO::PARAM_STR);

// Exécution de la requête
$oDatabase->Execute();

// On associe les données dans un tableau à deux dimensions associatif
$aServers = $oDatabase->Assoc();


So at the first line, I need to make a
chdir('../');
to include the necessary files (
header.php
).

I tested the script with Chrome and all worked fine but when I execute the script with command-line, PHP drop this error :

[14:40] root@dev.company.local / >> php -f /web/dev/company/public_html/dasPing/cron/cron.php
PHP Warning: require_once(./includes/header.php): failed to open stream: No such file or directory in /var/www/html/dev/diadeis/public_html/dasPing/cron/cron.php on line 7

Warning: require_once(./includes/header.php): failed to open stream: No such file or directory in /var/www/html/dev/diadeis/public_html/dasPing/cron/cron.php on line 7
PHP Fatal error: require_once(): Failed opening required './includes/header.php' (include_path='/usr/share/php') in /var/www/html/dev/diadeis/public_html/dasPing/cron/cron.php on line 7

Fatal error: require_once(): Failed opening required './includes/header.php' (include_path='/usr/share/php') in /var/www/html/dev/diadeis/public_html/dasPing/cron/cron.php on line 7


I searched why PHP drop this but I can't find any answer.

Do anyone knows why this is happening ?

Thank you !!

Answer Source

The current working directory would be where you are executing the script from, not where the script lives. You can get the directory that contains the script using the constant __DIR__

chdir(__DIR__ . '/../');