relative path in require_once doesn't work relative path in require_once doesn't work php php

relative path in require_once doesn't work


Use

__DIR__

to get the current path of the script and this should fix your problem.

So:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

Edit: slash problem fixed


for php version 5.2.17 __DIR__ will not work it will only works with php 5.3

But for older version of php dirname(__FILE__) perfectly

For example write like this

require_once dirname(__FILE__) . '/db_config.php';


In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }require_once THISBASEPATH.'cache/crud.php';/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php w.php e.php r.php cache/a.php cache/b.php setting/a.php setting/b.php

....