Search code examples
phpfilepath

Why ./ is not being recognized as current directory in my php file?


I have the following file hierarchy: screenshot

and the require_once is somehow not working (Warning: require_once(./AutentificadorJWT.php): failed to open stream: No such file or directory in C:\xampp\htdocs\clases\usuario.php on line 2) As far as I know ./ points to the current directory. Now the following works: require_once 'AutentificadorJWT.php'; Why ./ is not working?


Solution

  • It can be quite difficult to know what directory is the current directory when you have a complex hierarchy of code. If you want to have a constant point of reference, then you can use $_SERVER['DOCUMENT_ROOT'] which defines the base of your code on your computer. So...

    require_once $_SERVER['DOCUMENT_ROOT'].'/base.php';
    

    Will work for base.php in the root of your project. The one problem I've had with this is that unit testing doesn't always have a lot of the $_SERVER variables set.

    Alternatively, you can use __DIR__ which is the directory of the current file. So if in your case you changed it to ...

    require_once __DIR__.'/AuthentifacdorJWT.php';
    

    This will always be relative to the directory of the file your working with.