Andelas
Andelas

Reputation: 2052

PHP to place page-generated title into <head>

We include a header.php file across all the pages on our site. So we could either place a single title in the header.php file which would be applied to the entire site, or have a custom header within each page to be more descriptive.

The problem is that in doing that, the title would be outside the head tags (which remain in the header.php file) and marked as invalid.

Is there some kind of function we can use to define a variable ($pageTitle) within the page, that will be displayed in head tag?

Thanks.

Upvotes: 4

Views: 7551

Answers (4)

Bryan
Bryan

Reputation: 347

The way I see it, you can still do all this work in your header:

<?php
include(...your config/connect file...);
mysql_query(... get page variables ...);
$pageTitle = stripslashes($titlefromDB);
?>
<html><head><title><?php echo $pageTitle; ?></head>

Thus concludes you header.php. Now include this on every page you want to use it, and follow with your <body></body></html>.

Just one idea, but anyway you go around this, you're going to have to connect to your DB first, check if page exists, if so set title as variable, then begin constructing html.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157893

Actually it should be this way

news.php:

<?
include "config.php"; //connect to database HERE.
$data = getdbdata("SELECT * FROM news where id = %d",$_GET['id']);
$page_title = $data['title'];
$body = nl2br($data['body']);

$tpl_file = "tpl.news.php";
include "template.php";
?>

template.php:

<html>
<head>
<title><?=$page_title?></title>
</head>
<body>
<? include $tpl_file ?>
</body>

tpl.news.php

<h1><?=$page_title?></h1>
<?=$body?>

plain and simple

Upvotes: 5

Matt
Matt

Reputation: 7212

It looks like you want a dynamic title on some pages?

<?php
$defaultPageTitle='Default Title'; //Default title
include('header.php');
?>

<?php
/* You would define $newPageTitle here if necessary
 (i.e. use $_SERVER['REQUEST_URI'] to get the URL
 and check a database for the $newPageTitle */
?>
<head>
<?php
if(isset($newPageTitle)){echo '<title>'.$newPageTitle.'</title>';}
else{echo '<title>'.$defaultPageTitle.'</title>';}
?>
</head>

Upvotes: 1

Jim
Jim

Reputation: 18853

Ummm.....

<?php 
$pageTitle = "Test";
include('header.php');
?>

EDIT

Then in your header.php

<head>
    <title><?php echo $pageTitle; ?> </title>
</head>

Upvotes: 2

Related Questions