Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find parent directory in PHP?

I have this code in HTML that works fine:

<link href="/mywebsite/styles.css" rel="stylesheet" type="text/css"/>

However, this code in PHP does not:

require('/mywebsite/db.php');

Both db.php and styles.css are in the same directory. I can use:

require(dirname(__DIR__) . '/db.php');

But that seems rather ugly. Am I missing something obvious?

like image 291
Ay Go Sis Avatar asked Sep 05 '25 03:09

Ay Go Sis


1 Answers

Am I missing something obvious?

Yes. :)

require('/mywebsite/db.php');

/ is the system root (C:\ if you're a Windows guy). It's not relative to the URL your site is hosted at, it's relative to the system the site runs on. I'd guess your site is saved somewhere like /users/aygosis/webroot/index.php. /mywebsite/db.php probably does not exist on your system.

require dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'db.php'

is actually a good way to do this. You could also establish a base in a file that's available everywhere and make all includes relative to it:

define('ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);

...

require ROOT . 'db.php';
like image 91
deceze Avatar answered Sep 07 '25 16:09

deceze