Skip to content
Advertisement

Dynamic Title Tag in PHP

I am trying to dynamically populate the title tag on a website. I have the following code in my index.php page

<?php $title = 'myTitle'; include("header.php"); ?>

And the following on my header page

<title><?php if (isset($title)) {echo $title;}
else {echo "My Website";} ?></title>

But no matter what I do, I cannot get this code to work. Does anyone have any suggestions?

thanks

Advertisement

Answer

This works (tested it – create a new folder, put your first line of code in a file called index.php and the second one in header.php, run it, check the title bar).

You should double check if those two files are in the same folder, and that you’re including the right header.php from the right index.php. And ensure that $title is not being set back to null somewhere in your code.

Learn more about Variable Scope here.

Edit: Examples of visible changes would be:

TEST1<?php $title = 'myTitle'; include("header.php"); ?>

<title>TEST2<?php if ...
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement