tags:

views:

91

answers:

2

I would include a php header (mysite.com/header.php) in all the pages from a site.

How to do it properly?

There are relative links:

<?php include_once 'header.php'; ?>
<?php include_once '../header.php'; ?>

And this didn't help:

<?php include_once '/header.php'; ?>
A: 

Try

<?php require_once('./header.php'); ?>

And adjust the path as needed, i.e. ../header.

Josh K
Is there a way to set it relative to the root, not relative? I wouldn't adjust every time I create or move the file.
serhio
ah. noticed that require not include... is a difference?
serhio
Won't be downvoting but absolute filepaths in PHP are not URL-based but filesystem-based. So your last sentence is false.
Daniel
@serhio, the difference between require and include is simply that if require fails php generates a (fatal) E_ERROR error instead of an E_WARNING.
Daniel
@Daniel: I stand corrected.
Josh K
`<?php require_once '/header.php'; ?>` does not work from by e.g. "login/index.php", but `<?php require_once '../header.php'; ?>` works
serhio
../header.php should work if your header.php file is within one folder of your root. Ex: If your root folder has index.php, and you want to access your header.php which let's say is in a folder called header, you need to write "../header.php.
ggfan
maybe the "problem" is that "DOCUMENT_ROOT" gives me: `/home/mySite/public_html`
serhio
@ggfan: yes, I know this. As I said, "../header" works, but not '/header'
serhio
+1  A: 

You can do something like this:

include($_SERVER["DOCUMENT_ROOT"] . "/header.php");
Joel Alejandro
]."/header.php");
serhio
I hate to be a pedant but you really should use single quotes. Not only because they look nicer (subjective, I guess), but are more efficient as they are treated as literals thus will be used unevaluated.
Tim Green
Thanks for the heads-up! I'll keep that in mind. Oh, and you shouldn't introduce yourself with "I hate to be a pedant but--". I mean-- your comment is really instructive, and I've learnt something new today! Thanks again :)
Joel Alejandro
Hey @Tim I hate to be a pedant but there is no difference. Stop spreading stupid ancient rumors. Go learn profiling. There is nothing instructive in this post, but only wild superstitions. there is nothing to evaluate in the "/header.php" string
Col. Shrapnel
That's the point. We know there is nothing to evaluate in the string, but how does PHP? It doesn't, it checks the string to see if there are any variables. Give it a literal string, and it won't check. That's my point.
Tim Green
Alright, let's benchmark both quotes. How much will be the difference? 0.0000000000001 secs? I don't think it's worth to argue about the (non) efficiency of using double or single quotes...
Joel Alejandro