How to change TITLE dynamically after the header is included [duplicate] - php

This question already has answers here:
How to dynamically change a web page's title?
(20 answers)
Closed 8 years ago.
I would like to change the title of the HTML page based on the content, but im including only the content below the header part, so i have to change the title from this included php. To explain:
<html>
<header><title>I would like to change</title></header>
<!--CONTENT-->
<?
include "pages/some_page.php";
?>
</html>
How could i do that? Anyone can help in this?

You cant do that without a nasty hack.
What you should do is perform all your logic BEFORE you output html. A simple example follows:
<?php
//index.php
//perform logic and set variables before any html
$page = isset($_GET['menu'])?$_GET['menu']:'home';
switch($page){
case 'home':
$title = ' welcome to myco.ltd';
$content = 'pages/home.php';
break;
case 'about':
$title = 'about us';
$content = 'pages/about.php';
break;
case 'contact':
$title = 'get in touch';
$content = 'pages/contact.php';
break;
}
//the following html could be in a separate file and included, eg layout.php
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<!--menu and other shared html here-->
<?php include $content;?>
<!-- shared footer stuff here-->
</body>
</html>
This is essentially a VERY barebones router script, an essential component of any framework. I would highly recommend you consider a lightweight framework rather than write everything from scratch. http://fatfreeframework.com/home would be a great start

The function below will let you change document title, meta keywords and meta description. You may use it anywhere in your application.
Just be sure to turn on output buffering using ob_start() before the function is called. I prefer including it at the top of application, just after all global settings are loaded.
function change_meta_tags($title, $keywords, $description){
$output = ob_get_contents();
if (ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/", "/<meta name=\"keywords\" content=\"(.*?)\" \/>/", "/<meta name=\"description\" content=\"(.*?)\" \/>/");
$replacements = array("<title>$title</title>", "<meta name=\"keywords\" content=\"$keywords\" />", "<meta name=\"description\" content=\"$description\" />");
$output = preg_replace($patterns, $replacements, $output);
echo $output;
}

Use javascript in some_page.php .
<?php echo "<script>document.title = '".$dynamicTitleVariable."';</script>"; ?>

Pending what you are trying to base the content off of, this could easily be done via an MVC-style setup. In your controller, you would generate the title based off of content that could be grabbed and pass this through to the view as a variable. Then, in your view have the title be dynamically set:
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
</html>
This should also work fine with SEO capability, as crawlers will be able to interpret this far better than they would JavaScript.

Related

Using PHP as Template Engine and having a thin Template

I'm using PHP as a template engine per this suggestion: https://stackoverflow.com/a/17870094/2081511
I have:
$title = 'My Title';
ob_start();
include('page/to/template.php');
$page = ob_get_clean();
And on page/to/template.php I have:
<?php
echo <<<EOF
<!doctype html>
<html>
<title>{$title}</title>
...
EOF;
?>
I'm trying to remove some of the required syntax from the template pages to make it easier for others to develop their own templates. What I would like to do is retain the variable naming convention of {$variable} but remove these lines from the template file:
<?php
echo <<<EOF
EOF;
?>
I was thinking about putting them on either side of the include statement, but then it would just show me that statement as text instead of including it.
Well, if you want a VERY simple templating solution, this might help
<?php
$title = 'My Title';
// Instead of including, we fetch the contents of the template file.
$contents = file_get_contents('template.php');
// Clone it, as we'll work on it.
$compiled = $contents;
// We want to pluck out all the variable names and discard the braces
preg_match_all('/{\$(\w+)}/', $contents, $matches);
// Loop through all the matches and see if there is a variable set with that name. If so, simply replace the match with the variable value.
foreach ($matches[0] as $index => $tag) {
if (isset(${$matches[1][$index]})) {
$compiled = str_replace($tag, ${$matches[1][$index]}, $compiled);
}
}
echo $compiled;
Template file would look like this
<html> <body> {$title} </body> </html>

PHP create a nicer way to echo variables

I am looking for a way to replace <?php echo $something; ?> with another notation like {$something}. But: No smarty or sth similar is used!
More detailed:
At the moment, I got a .php file (with some variables inside), which includes the file "template.php". In this template file, I don't want having to use the (not very user-friendly) php notation, but replace certain strings inside this file like mentioned above. Is there any way to do so? It would be probably the best, if you could replace strings like <title></title> with <title><?php echo $title; ?></title>.
Maybe (my thoughts) I should just write the whole code into a php variable, then do some preg_replace and echo it? Or is there a more beautiful solution?
Did a similar thing several years ago wherein I had to replace several variables in an email template. What I ended up implementing was doing a str_replace on several tags. Like you, I don't want to have PHP notations or to escape characters in the template file as much as possible
Example:
template.php
<html>
<head>
<title>[EMAIL_TITLE]</title>
</head>
<body>
Hello [USER_NAME],
Login here [LOGIN_LINK].
</body>
</html>
processor.php
$body = file_get_contents( 'template.php' );
str_replace( '[EMAIL_TITLE]', $emailTitle, $body );
str_replace( '[USER_NAME]', $userName, $body );
str_replace( '[LOGIN_LINK]', $userName, $body );
I've sinced changed implementation though to make use of PHP short tags. Using the same previous example, you could try:
template.php
<html>
<head>
<title><?= $params['title']; ?></title>
</head>
<body>
Hello <?= $params['userName']; ?>!
</body>
</html>
processor.php
$params = array(
'title' => $siteTitle,
'userName' => $userName
);
ob_start();
require_once( 'template.php' );
$body = ob_end_clean();
There are a few notations you can try. One that I prefer for templates is simply:
<?php
echo <<<HTML
<html>
<head>
<title>$title</title>
</head>
<body>
$body
</body>
</html>
HTML;
?>
And then in your content file, you do something like:
<?php
$title = 'My Page!';
$body = '<p>My Content!</p>';
include './template.php';
?>
With this, you don't have to escape singe and double quotes, and it's easy to make changes later.
You can also read in the file to a string and use preg_replace like you said. The easiest way would be with an array to manually go through the file and pull out the place holders. But this is a slow solution if you have high traffic and a lot of variables.

Get php out of body

I've read and heard it is really sensible to separate your PHP and HTML tags as much as possible. Now my question is how should I do that? I couldn't really find the answer so I decided to ask you.
I was thinking about to use the POST function.
Check out my code:
<div class="aftelklok rondenSB">
<a href="?page=agenda">
<?php
// countdown function
// parameters: (year, month, day, hour, minute, seconds)
countdown(2013,2,24,18,0,0);
function countdown($year, $month, $day, $hour, $minute, $seconds)
{
// make a unix timestamp for the given date
$the_countdown_date = mktime($hour, $minute, $seconds, $month, $day, $year, -1);
// get current unix timestamp
$today = time();
$difference = $the_countdown_date - $today;
if ($difference < 0) $difference = 0;
$days_left = floor($difference/60/60/24);
$hours_left = floor(($difference - $days_left*60*60*24)/60/60);
$minutes_left = floor(($difference - $days_left*60*60*24 - $hours_left*60*60)/60);
$seconds_left = floor($difference - $days_left*60*60*24 - $hours_left*60*60 - $minutes_left*60);
if($difference > 0){ echo "Nog ".$days_left." dagen ".$hours_left." uur .$minutes_left." minuten tot de dienst"; }
else{ echo "De vorige dienst is afgelopen."; }
}
?>
</a>
</div>
So what i want is just the echo but then have all the php code not in my div but above the html code. like:
<?php ..... ?>
<html>
<body>
echo
</body>
</html>
As pemeon said, Smarty is quite a smart (pun intended) approach for that.
If you want to learn more about the backgrounds, you might want to google for "Model-View-Controller in php" or something like that. Basically, it's about separating your view (all the presentation stuff, e.g. HTML) from your code logic (controller) and your data objects / sources (model).
Smarty is nice but you'll need a bit of learning time to figure out how the template engine is designed, how to use it and how to apply it to your specific challenges.
If you don't want such a big solution at the moment and want to start a bit smaller and easier, you could write your own very simple template "engine" around the functions file_get_contents(...) and str_ireplace. The idea looks like this: You put your HTML stuff in template-files (for example *.html or *.tpl file ending) that don't contain any php code but place holders for dynamically created content:
Example: main-layout.tpl
<html>
<head><title>${Title}</title></head>
<body>
<img src="yourfancylogo.png" alt="Header logo"><br>
Here some navigation | ... | ... <br>
${Content}
<hr>
<div id="footer">© 2013 John Doe - Contact us</div>
</body>
</html>
Example: welcome.tpl
<h1>Hello, ${Username}! Nice to see you!</h1>
<p>So your username is ${Username}? Then you might want to read our terms of service before starting to use our app:</p>
<pre>${TOS}</pre>
Example: tos-document.txt
1) An apple a day keeps the doctor away!
2) No Smoking!
3) ...
In your php script you do something like this:
<?php
$template = file_get_contents('main-layout.tpl');
if (isset($_GET['requestedpage'])) {
// Parameter given!
$requestedPage = $_GET['requestedpage'];
} else {
// No page parameter. Assume "home".
$requestedPage = "home";
}
$username = "Monty"; // get from session data
if ($requestedPage == 'home') {
// -- begin handler code for page "home" --
$title = "Start Page - Welcome";
$content = file_get_contents('welcome.tpl');
$tos = file_get_contents('tos-document.txt');
$content = str_ireplace('${TOS}', $tos, $content);
// -- end handler code for page "home" --
} else if ($requestedPage == 'aboutus') {
...
} else {
$title = "Page Not Found - Error";
$content = file_get_contents('error404.tpl');
$content = str_ireplace('${PageThatWasNotFound}', htmlentities($requestedPage), $content);
}
$output = str_ireplace('${Content}', $content, $template);
$output = str_ireplace('${Title}', htmlentities($title), $output);
$output = str_ireplace('${Username}', htmlentities($username), $output);
die($output);
?>
Using such a separation of the template and the data to insert, you can later modify your layout / template without having to touch your php scripts. For example, if you want to modify your header or footer shown on all pages, you have a single point of change as you can modularly assemble your site from several template-bricks.
To keep the php source above readable, while your source is becoming larger, you can put all the handler codes into separated php files. You'd include them by include or require into your main source file.
But watch out: You have to escape all placeholder values that might come from user inputs - regardless, if you get them from a database or directly from $_GET or $_POST (-> XSS vulnerabilities). All input is evil!
You cannot use a php function or variable outside of a PHP block. However, it is possible to store a value in a php variable then use it in a tiny PHP block.
For example:
<?php
// ...
$foo = 42;
// ...
?>
Then
<html><body>
<p>Answer is <?php echo $foo; ?></p>
</body></html>
or
<html><body>
<p>Answer is <?= $foo; ?></p>
</body></html>
You could put your php in a separate file, and then use include or require.
do_stuff.php:
<?php
// some calculations
echo "stuff";
?>
Then in your html...
index.php:
<html>
<body>
<?php include 'do_stuff.php'; ?>
</body>
</html>
About include
The best way is to use some template engine like smarty or twig. If you do not have time to learn you can for now just write code at the top and when you want to use some calculations in i.e you use .
<?php
// calculations
$foo = 'foo';
?>
<html>
<body>
<div><?=$foo?></div>
</body>
</html>
And when you start to use this kind of 'separation' (php code in the top of the file) and html at the bottom and you will use this shortcut version of the echo function, you will easily transform into using template system.
The goal should not be keeping php away from html code, the goal should be keeping business logic from presentation logic. One of the ways to do this is utilising a Model-View-Controller layout, or you could use one of many other paradigms. The main point of this approach is making changing one part independent of the other: imagine creating a separate mobile or json front end, that does all the exact same logic, but outputs it completely differently. If the business logic and presentation logic are completely entangled, you will have a hard time, probably needing to both reproduce or blatantly copy code, as well as creating two different branches that need to be kept in-sync, making maintaining it a nightmare.
I`m using right now this sort of frame, its sort of like the frame MrSnurb made, but then in HTML in stead of php. what do you think about this framework guys?
<?php
if(isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = "home";
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Younited - <?php echo $page; ?></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/slides.min.jquery.js"></script>
</head>
<body>
<div class="container ronden">
<?php
include "partials/header.php";
include "partials/menu.php";
?>
<div class="content">
<?php
if (file_exists("partials/pages/".$page.".php")) {
include "partials/pages/".$page.".php";
}
else{ echo "<p>De pagina <b>".$page."</b> bestaat niet.</p>";
}
include "partials/sidebar.php";
?>
</div>
</div>
<?php
include "partials/footer.php";
?>
</body>
</html>
Use some template engine like smarty. To create template of your html code and push there varibles.

What method should I use for later set a variable and then echo the page title

I'm trying to avoid to query my database twice: for set <title> attribute and also for echo the page title. I want to query it just one time:
Example:
<html>
<head>
<?php
// how should I use here ob_start() ? Is there any other possible way to achieve this?
$title = "";
echo '<title>', $title, '</title>'; // this should be in the end <title>value of $row['page_title']</title>
?>
</head>
<body>
<?php
$sql = $mysqli->query("MY QUERY");
$row = $sql->fetch_assoc();
$title = $row['page_title']; // I want that this assignment to set the variable in the top
// I know that for this job I can use ob_start() but I didn't used it until now
// and I will really appreciate any help from you.
?>
<h1><?php echo $title; ?></h1>
</body>
</html>
I know that I can do the query before echo the title attribute but I don't want to do it like that. Do you have any suggestion? or can you show me how to use that ob_start() / ob_clean() functions?
Thank you!
Shift the query to the top of the code and reuse the variables!
<?php
$sql = $mysqli->query("MY QUERY");
$row = $sql->fetch_assoc();
$title = $row['page_title'];
?>
<html>
<head>
<?php echo '<title>', $title, '</title>'; ?>
</head>
<body>
<h1><?php echo $title; ?></h1>
</body>
</html>
ob_start();, in usual sense, won't help you have. However, you can use ugly solution like this:
ob_start();
echo '
<html>
<head>
<title>{title}</title>
</head>
<body>
';
$header = ob_get_clean();
// and then, when you know your title
echo str_replace('{title}', $known_title, $header);
But I strongly recommend taking another approach. You need to choose and fill the template after all data has been gathered and you know all details about which template you want. If you start echoing different parts preemptively, you will get more and more troubles. Now you need to change title for some pages. Then you will need to add css file for specific page and you will have to do that ugly business again. Why not do it the right way?

Add to page title tag based on variable from URL

I have seen the following thread but it's a bit beyond me...
How can I change the <title> tag dynamically in php based on the URL values
Basically, I have a page index.php (no php in it just named to future proof - maybe now!). It contains numerous lightbox style galleries which can be triggered from an external link by a variable in the URL - e.g. index.php?open=true2, index.php?open=true3, etc.
I would like the index.php title tag - to include existing static data + append additional words based on the URL variable - e.g. if URL open=true2 add "car gallery", if URL open=true3 add "cat gallery", if URL has no variable append nothing to title.
Can anyone assist? I have been searching but either missed the point of posts or it hasn't been covered (to my amateaur level).
Many thanks. Paul.
At the top of your php script put this:
<?php
# define your titles
$titles = array('true2' => 'Car Gallery', 'true3' => 'Cat Gallery');
# if the 'open' var is set then get the appropriate title from the $titles array
# otherwise set to empty string.
$title = (isset($_GET['open']) ? ' - '.$titles[$_GET['open']] : '');
?>
And then use this to include your custom title:
<title>Pauls Great Site<?php echo htmlentities($title); ?></title>
<title>Your Static Stuff <?php echo $your_dyamic_stuff;?></title>
<?php
if( array_key_exists('open', $_GET) ){
$title = $_GET['open'];
}else{
$title = '';
}
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
The content of the document......
</body>
</html>
http://www.w3schools.com/TAGS/tag_title.asp
http://php.net/manual/en/reserved.variables.get.php
PHP can fetch information from the URL querystring (www.yoursite.com?page=1&cat=dog etc). You need to fetch that information, make sure it's not malicious, and then you could insert it into the title. Here's a simple example - for your application, make sure you sanitise the data and check it isn't malicious:
<?php
$open = "";
// check querystring exists
if (isset($_GET['open'])) {
// if it does, assign it to variable
$open = $_GET['open'];
}
?>
<html><head><title>This is the title: <?php $open ?></title></head>
PHP has lots of functions for escaping data that might contain nasty stuff - if you look up htmlspecialchars and htmlentities you should find information that will help.
Some of the other answers are open to abuse try this instead:
<?php
if(array_key_exists('open', $_GET)){
$title = $_GET['open'];
} else {
$title = '';
}
$title = strip_tags($title);
?>
<html>
<head>
<title><?php echo htmlentities($title); ?></title>
</head>
<body>
<p>The content of the document......</p>
</body>
</html>
Otherwise as #Ben has mentioned. Define you titles in your PHP first to prevent people from being able to directly inject text into your HTML.

Categories