Short answer version: You can't. You'll get an 'Undefined variable' notice if you do that.
I find it is usually much more convenient to have a header.php
(and a footer.php
for that matter) which gets included in the index, home, contact or whatever other file. The advantage is that you don't have redundant code, and if you need to make a modification in the header or footer, you need to only modify one file.
So for example, 'about_us.php' would look like:
<?php
include('path/to/header.php');
#body goes here
include('path/to/footer.php');
?>
And your header would be something like:
<?php
$title = ucfirst(str_replace('_', ' ', substr(basename($_SERVER['PHP_SELF']), 0, -4));
?>
<html>
<head>
<title><?php echo $title; ?> page</title>
<meta name="description" content="this is the home page" />
<meta name="keywords" content="home, awesome, yes" />
</head>
<body>
The $title
variable will be the file name, minus the extension, with all underscores replaced by spaces and the first letter of the first word capitalized. So basically about_us.php
would be converted into "About us". This is not necessarily a general solution, but I gave it as an example keeping in mind that you wanted to use a dynamic title in your original example. For dynamic description and keywords, based on the file name you could also assign different values with the help of a switch()
statement.
UPDATE:
Another solution, although kind of the reverse of what you're asking, but at the same time much closer to what you're looking for would be to write the header.php
like
<html>
<head>
<title><?php echo $title; ?> page</title>
<meta name="description" content="<?php echo $desc; ?>" />
<meta name="keywords" content="<?php echo $keywords; ?>" />
</head>
<body>
... the footer like ...
</body>
</html>
... and then include them in your other files:
<?php
$title = 'Your title';
$desc = 'Your description';
$keywords = 'The, big, brown, fox, jumps, over, the, lazy, dog';
include('path/to/header.php');
?>
<!-- body goes here -->
<?php
include('path/to/footer.php');
?>
This way, you are assigning all the variables BEFORE you are including the files in which they are being referenced, you have distinct files for all the links and you don't need fancy switches. Also as a side note, wrapping the body's HTML in PHP is simply bad practice. Try to keep the HTML separated from the PHP as much as possible in general. It will help both you, and whoever is going to do work on the code in the future.
Hope this helps !