Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - how to change title of the page AFTER including header.php?

Tags:

php

title

page.php:

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

header.php:

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

I want my title to be set after including the header file. Is it possible to do this?

like image 590
John Stockton Avatar asked Oct 22 '12 10:10

John Stockton


People also ask

How can I change website name in PHP?

php ob_start(); include("header. php"); $buffer=ob_get_contents(); ob_end_clean(); $buffer=str_replace("%TITLE%","NEW TITLE",$buffer); echo $buffer; ?> The title is now <title>Backup Title</title>

What PHP can do with header () command?

The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).

Why my header is not working in PHP?

The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error. Like following example, there should not be any output of even a space before the headers are sent.

What does the function header sent in PHP return?

The headers_sent() function is an inbuilt function in PHP which is used to determines whether the header is successfully sent or not. The headers_sent() function returns True if header sent successfully and False otherwise.


2 Answers

expanding on Dainis Abols answer, and your question on output handling,

consider the following:

your header.php has the title tag set to <title>%TITLE%</title>; the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.

then, you can use output buffer like so

<?php
    ob_start();
    include("header.php");
    $buffer=ob_get_contents();
    ob_end_clean();

    $buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
    echo $buffer;
?>

and that should do it.

EDIT

I believe Guy's idea works better since it gives you a default if you need it, IE:

  • The title is now <title>Backup Title</title>
  • Code is now:
<?php
    ob_start();
    include("header.php");
    $buffer=ob_get_contents();
    ob_end_clean();

    $title = "page title";
    $buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);

    echo $buffer;
?>
like image 88
we.mamat Avatar answered Sep 19 '22 05:09

we.mamat


1. Simply add $title variable before require function

<?php

$title = "Your title goes here";
require("header.php");

?>

2. Add following code into header.php

<title><?php echo $title; ?></title>
like image 31
J Perera Avatar answered Sep 23 '22 05:09

J Perera