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?
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>
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).
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.
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.
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:
<title>Backup Title</title>
<?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;
?>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With