If I have session_start(); at the top of my header page is it alright to include $page_title before the header page?
$page_title = 'Some Title';
include '../includes/header.php';
Yes. As long as you don't output anything before it, you should be ok...
The reason is that session_start sends a few HTTP headers. So if you've already outputted anything (including errors), it will fail, and as such won't start.
The way around that, is to setup output buffering at the top of the file. Just make ob_start(); appear at the top of the page. That way, no matter what happens (within reason), you should be ok (as in any output will be "captured" by the buffer, and hence not interfere with the session comamnd)...
Edit: As requested, an example:
<?php
echo 'foo';
include '../includes/header.php';
Won't work since you've outputted something...
<?php
include 'non/existant/file.php';
include '../includes/header.php';
Won't work since the first include statement will emit a warning because it couldn't find the file...
FooBar<?php
include '../includes/header.php';
Won't work since you're outputting something before hand (the text before the <?php line)...
<?php
ob_start();
echo 'foo';
include '../includes/header.php';
WILL work, since the output is captured by the buffer...
FooBar<?php
ob_start();
include '../includes/header.php';
Will not work, since the output buffer is started after the output is started...
<?php
include 'some/valid/file.php';
include '../includes/header.php';
May or may not work. It depends if the first included file outputs anything. If it does, then it won't work (So toss a ob_start() before hand to try to ensure it works)...
Oh, and you'll likely want to change the include to require since you don't want to continue if it doesn't find the file...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With