3

My PHP-based site files start off with

<?php include("PHP/header.php"); ?>

which includes all the HTML (metadata, scripts, etc.) shared by every page - along <head> and <title>. The options I've considered for dynamic page titles are:

<title id="title">...</title>
...
<script>window.onload=function(){document.getElementById('title').innerHTML="New title"}
</script>

and

<?php include("PHP/header1.php"); ?> <!-- code in header.php before <title> -->
<title>New title</title>
<?php include("PHP/header2.php"); ?> <!-- code after </title> -->

(I intend the same for page descriptions - omitted for brevity.)

Which of these is preferable for search engine optimization - do better approaches exist? Lastly, any performance differences to note (scripts vs. php, etc)?

0

2 Answers 2

5

Set the title as a variable and pass it to your include:

<?php 
    $page_title = 'Welcome to my site';
    include("PHP/header.php");
?>

Then inside your header PHP you can use that variable. Here I'm using htmlspecialchars to ensure that <>& are properly escaped if they are used in the title.

<title><?php echo htmlspecialchars($page_title); ?></title>

You could even put code in your header PHP to check that the title has been set and to use a default title if it hasn't been:

if (empty($page_title)) {
    $page_title = 'This page gets this default title';
}

You could use the same technique for other items that you might want to customize in the header such as the meta description.

0
1

The most reliable and correct way to set the optimal SEO method would be to set the headers within the web server configuration and not just those PHP headers because that would only result in covering the title for webpages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.