简体   繁体   中英

How can I define the constant for absolute path only once in PHP?

I have the following files:

  • admin/config.php
  • header.php
  • index.php
  • contact/index.php

Both index.php and contact/index.php call header.php. And header.php calls admin/config.php which sets the website root path WEBSITE_HTTP_ROOT . I need WEBSITE_HTTP_ROOT to be able to provide the link to the main page.

Here is header.php:

<?php
require_once('./admin/config.php');
?>
  <div id="menu">
    <a href="http://<?php echo WEBSITE_HTTP_ROOT; ?>" id="logo">website</a>
  </div>

The line require_once('./admin/config.php'); works when called by index.php, but does not work when called by contact/index.php, because the working folder is different.

How can I define the constant for absolute path only once? and be able to call it from anywhere? or how to best avoid the above problem?

One solution is to always include files using the relative path from the current php file location obtainable using dirname(__FILE__) .

For example, in header.php , you would include config.php with:

require_once(realpath(dirname(__FILE__)) . './admin/config.php');

Then in index.php :

require_once(realpath(dirname(__FILE__)) . './header.php');

and in contact/index.php :

require_once(realpath(dirname(__FILE__)) . '../header.php');

You could define a base url parameter:

define ( 'BASEURL', 'http://www.domain.com' );

And then use: <a href="<?= BASEURL ?>/header.php"> Or for front page, just

<a href="<?= BASEURL ?>">

Otherwise, just reference it as:

<a href ="/header.php">

or for frontpage:

 <a href ="/">

In fact, I found a work-around (for now) since I did the include of config.php already in the main index.php, I did not need to re-include the config.php in the header.php.

So following code works fine:

<?php
?>
  <div id="menu">
    <a href="http://<?php echo WEBSITE_HTTP_ROOT; ?>" id="logo">website</a>
  </div>

this does not really answer the question... but it fixes my problem. Might be useful for someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM