I have this class:
class PageBuilder {
public function GetHeader() {
include(dirname(dirname(__FILE__)) . '/template/header.php');
}
}
Which when called will insert the header file into my page. All is good.
$page_builder->GetHeader();
In the header.php
is the top of the HTML
file which includes a menu. My problem is, depending on where the PageBuilder
gets called from changes the menu link URL
s.
How do I make sure they are always relative to the root folder.
dirname(__FILE__)
doesn't work because it turns the URL
into file:///
, also I really don't want to append the entire http://www.blahblah.com/blah
because if it is relative to the root it doesn't matter about any of that.
EDIT
So as someone posted you can use $_SERVER['']
but which one is reliable, no doubt PHP
will have put in some blinding caveats.
See I was thinking $_SERVER['SERVER_ADDR']
or $_SERVER['SERVER_NAME']
or $_SERVER['HTTP_HOST']
.....
Going $_SERVER['HTTP_HOST']
for now .. result is fail.
Just prefixing with /
resolves to the localhost root so my links are localhost/admin/profile.php
rather than localhost/TestApp/admin/profile.php
, Do I have to actually specify that it sits in folder named TestApp
?
After trial and error with the help of @deceze I simply pass my URL
through a routing class which prefixes the URL
with '/TestApp/' this can be change easily if the project gets moved because the use of classes.
So I do:
<a href="<?php $url_routing->ParseUrl('admin/account/logout.php') ?>">Log Out </a>
Gets passed through:
public function ParseUrl($url) {
return '/TestApp/' . $url;
}
It is hardly best practice, but there can't be best practices with a language that doesn't follow any itself.
Looking at @Anthony answer of using $_SERVER['PHP_SELF'];
it does always give the TestApp
folder. Needs more looking into but I will take that. I assume its relative to the server address.
You need to differentiate between local file paths and URLs first and foremost. The two have nothing to do with one another. PHP with its __FILE__
and dirname()
and related parts is dealing only with local file paths on the server's hard disk. URLs on the other hand are entirely arbitrary strings that you need to put together in a sensible way. There are an infinite ways how any one particular file may be referred to by a URL, it's up to you to bring order into this.
You could try to figure out which URL was requested using the various paths available in $_SERVER
and construct relative URLs based on that. However, this is rather error prone and overly complicated. Rather you should be using root-relative URLs. I.e. instead of
foo/bar.html
which is relative to the URL the browser is currently on, you always use
/foo/bar.html
which always refers to the same URL regardless of what URL it's currently relative to.
If you need a prefix for all your URLs, I'd create a wrapper function which adds this as needed based on configuration or on automatically figuring out its own root URL based on $_SERVER
.