Using Filenames for Page Titles Using PHP A Simple But Not Extensive Solution

The original question from site commenter Charlie on my post about using a PHP snippet to specify webpage titles based on the page name:

Isnโ€™t there a way to just look at the php file itself and take itโ€™s name and omitting the URL and file extension? It would save a lot of hassle of adding extra lines.

I prefer to take the time to specify specific titles for different pages. To me, it’s worth the extra time and code. I got to considering how, if you wanted to simply use your file names for page titles, how you’d go about coding that. This is what I came up with:

//get the file path
$file = basename($_SERVER['PHP_SELF']);
//remove the file extension so that we only have the file name
$currentpage = basename($file,".php");

//output it as the page title
echo "<title>$currentpage</title>"; 

The problem with this method, however, is that it doesn’t capitalize the first letter of each word nor does it put spaces in between each word. So, if your filename is awesomefilename.php, then your page title will be awesomefilename rather than something more suitable like Awesome File Name. I’m sure that someone could code something up that both capitalizes and adds spaces, but that would take a lot more time and code.

4 comments

  1. Kim Enders ( User Karma: 0 ) says:

    It could work if you simply put spaces between words in your page names. For example, if you named a file A New Beginning.php, you could use the code I provided on the post and it would achieve what you’re trying to do. Just remember, however, that the link for that page would look like this: A%20New%20Beginning.php. Of note, if you have any additional parameters after .php (i.e. ?id=home), those won’t show up in your title.

  2. Charlie says:

    Yes, I see now. Awesome solution. Perhaps first letter of a word could be capitalized, but your explanation kind of took away my trail of thought. I understand why my idea wasn’t a valid one.

    However, as a php n00b, I’ve been working on my own website. Doing a few things here and there to test. Is it possible to use the name of a ‘php included’ file as the title? For instance I did flat file inclusion as I am still unaware of the possibilities of MySQL. My page would get id=?home as the filename is home.php but is it possible to get that filename in the header? Perhaps exclude the + sign when I create a file name with two words and an open space in between? Or should I think indeed of what you did and somehow combine this with my flat file inclusions?

    Thanks again!

Leave a Reply

Your email address will not be published. Required fields are marked *