Ok, well here's a basic example. Lets suppose we take a site that has a common header and footer across all pages, and only the main content changes. The header and footer can still contain variables that might change per page, for example the page title in the <title></title> html tags. So lets take one example of such a page, called foo.php (could be main.php, aboutus.php, contactus.php etc..etc). We also want to separate out foo.php's php code from it's html so it's easier to update at a later stage.
So header.php might look like:
Code: Select all
<?php
//this is header.php
?>
<html>
<head>
<title><?php echo empty($title) ? 'a default title' : $title ?></title>
</head>
<body>
<div class="header">
PUT THE HEADER HTML HERE. BASICALLY ANYTHING BEFORE THE MAIN CONTENT
</div>
<div class="maincontent">
and footer.php might look like
Code: Select all
<?php
//this is footer.php
?>
</div> <!-- closes the main content div in the header -->
<div class="footer">
PUT THE FOOTER HTML HERE. BASICALLY ANYTHING AFTER THE MAIN CONTENT
</div>
</body>
</html>
and foo.php could look like:
Code: Select all
<?php
//this is foo.php
$title = 'This is the main page';
$welcomemessage = 'Welcome to my site';
require_once 'header.php';
require_once 'theme/foo.html.php';
require_once 'footer.php';
?>
Here we've moved foo.php's html code into another file, this has several advantages which i'll mention in a moment

So theme/foo.php might look like (which holds foo.php's html)
Code: Select all
<?php
//this is foo.html.php
?>
<b><?php echo $welcomemessage ?></b>
whatever you want in foo.php can go here.
foo.php is basically the main page content, surrounded by
the header and footer
All this might look too complicated and nothing to do with what you are after, but it's the basis of a template system. With this each content page (main.php, foo.php, aboutus.php, contactus.php etc) has full control over the header and footer, so it can alter the page title etc..
Also, say you want to have multiple site themes (look and feels) then all you need to do is create some new html templates and you're done, you don't need to alter the code at all (well a little in my examples as i hard coded the theme directory). So back to your original question ... using this method then foo.php (or main.php in your code) can set $title before header.php is called, with your current code this isn't possible as the <title></title> tags come before main.php even has chance to alter it.
I apologise if this is too confusing (and i can see how it could be) but this is sort of a long term solution to the problem you have now, and it offers great flexibility). Please, please just sayb if it's too much and just ignore it, i won't be offended

But the basic answer to your question is the same, you need to have main.php come before the page that has the <title></title> tags in it.