Home > Software engineering >  Why I have to use double ../ when using __dir__ in this case
Why I have to use double ../ when using __dir__ in this case

Time:10-03

File Paths

C:\xampp\htdocs\zcron\x.php
C:\xampp\htdocs\zzz\config.php

I am including config file into x.php file. To include the config file I need to go one directory back outside zcron directory.

So this works

`require '../zzz/db/config.php'`;

but when I use

require __dir__.'../zzz/db/config.php';

It gives me an error saying

Fatal error: require(): Failed opening required 'C:\xampp\htdocs\zcron../zzz/db/config.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\zcron\x.php on line 2

If i use double ../ then it works

<?php 
require __dir__.'../../zzz/db/config.php';
require '../zzz/db/config.php';
?>

Echoing __dir__ in my case outputs C:\xampp\htdocs\zcron which means I have to go one directory back so why single ../ doesn't work ?

CodePudding user response:

Because you forgot the slash between the dirname and the dot-dot. Look at the error, it's your clue! It just "happens to work" under Windows with your extra dot-dot because dots at the end of a filename are dropped (zcron.. is handled like zcron).

C:\xampp\htdocs\zcron/../zzz/db/config.php
                     ^
                     (this slash was missing)

So the solution is to use __dir__.'/../stuff' and not __dir__.'../stuff'.

CodePudding user response:

I think you have an error in your syntax add '/' befor '..' I think it will works

<?php 
require __dir__.'/../zzz/db/config.php';
require '../zzz/db/config.php';
?>
  • Related