开发者

How to find parent directory in PHP?

开发者 https://www.devze.com 2023-02-15 16:03 出处:网络
I have this code in HTML that works fine: <link href=\"/mywebsite/styles.css\" rel=\"stylesheet\" type=\"te开发者_如何学编程xt/css\"/>

I have this code in HTML that works fine:

<link href="/mywebsite/styles.css" rel="stylesheet" type="te开发者_如何学编程xt/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?


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';


The common method here is to define some filesystem related constants, and then use them, i.e. in my little home-grown MVC framework, I define the following:

if (!defined('DS')) {
    /**
     * Shorter Directory Separator Constant
     */
    define('DS', DIRECTORY_SEPARATOR);
}

if (!defined('ROOT')) {
    /**
     * Application Directory path Constant
     */
    define('ROOT', dirname(dirname(__FILE__)));
}

I then reference files like this:

require ROOT . DS . 'System' . DS . 'Library' . DS . 'compatibility.php';


In your php.ini configuration file, add the location of your website files to the include_path. This way it will search that directory when you call include() or require()

0

精彩评论

暂无评论...
验证码 换一张
取 消