PHP – Creating a Dynamic Page Title From its Filename

Creating a page title from its filename is easy in php. In this post I will show you how to do so in a few lines of code. In the beginning it gets the file name and if there’s any dashes in the name it replaces all of them with white spaces. Then it checks to see if the file name is index, if so it assign ‘home’ to the title instead of index.

 <?php
 // extract the filename
 $title = basename($_SERVER['SCRIPT_FILENAME'], '.php');
 // replace dashes with whitespace
 $title = str_replace('_', ' ', $title);
 // check if the file is index, if so assign 'home' to the title instead of index
 if (strtolower($title) == 'index') {
 $title = 'home';
 }
 // capitalize all words
 $title = ucwords($title);

Open your page in your text editor and include title.inc.php above the DOCTYPE:

<?php include('./includes/title.inc.php'); ?>

Then amend the title tag like this:

<title><?php $title ?></title>