Reputation: 14614
I have the following files:
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?
Upvotes: 1
Views: 2042
Reputation: 14614
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.
Upvotes: 0
Reputation: 4470
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');
Upvotes: 1
Reputation: 2272
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 ="/">
Upvotes: 0