How to get page <title> from content include into front controller - php

I'm using a PHP based front controller pattern such that index.php provides the page structure and template, and all content for each page is in include files within /pages/.
index.php
/pages/home.inc
/pages/about.inc
/pages/contact.inc
The include pages are mostly simple HTML so that clients can edit the pages without having to get into anything too complex.
The problem with this layout is that because all page information is in the page include, the <title> element can't get populated. I could put a $title variable in each include, but it loads after the head, which is too late:
<html>
<head>
<title><?php echo $title; ?></title> #$title is not set yet!
</head>
<body>
<?php include($content); ?> #now $title is set
</body>
</html>
It's important that the content files are self contained and mostly HTML, but with the ability to have PHP code as well, as I mentioned, because customers will be modifying these and adding too much complexity is a problem. Thus, for example, setting up a separate database of page titles won't work because customers won't update the database when they make new pages.
Edit: a typical page include might look like this.
<h1>Welcome</h1>
<p>blah</p>
<?php include("nav.php"); ?>
<p>more blah</p>
<p>more blah</p>
<p>more blah</p>
<?php
$pageJavascript = "alert('js!');";
$pageTitle = "Cyberdyne Welcome Page";
?>

Options:
1: Use output buffering
<?php
ob_start();
include($content);
$body = ob_get_contents();
ob_end_clean();
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $body; ?>
</body>
</html>
Pros:
The browser gets fully rendered page
More SEO-friendly (than the javascript title update)
No JS required
Cons:
Need to buffer all the page in memory
2: Set some kind of general title and update it later with javascript.
<script type="text/javascript">
with(document) {
window.title = <?php echo json_encode($title); ?>;
}
</script>
Pros:
You keep the same kind of flow You use now.
Cons:
Not SEO friendly
Requires javascript use

If there is a assumption the title is always on the first line:
"My page Title";
$filename = '/pages/home.inc';
$fileLines = file($filename, FILE_SKIP_EMPTY_LINES);
$title = yourFunctionThatStripsKomma($fileLines[0]);
Only bad thing is, is that you have to be sure the first line has the title.

Related

PHP program flow with multiple queries and arrays? [duplicate]

I'm looking for advice on the best practice for separating site content up into logical blocks. I want a header and footer that are constant throughout the site, so that if I have several pages of different content, they will all look as below — changes made to the header and footer then update automatically without me having to change each individual page.
<?php
include 'header.php';
?>
<body>
<p>page content here</p>
</body>
<?
include 'footer.php';
?>
The header.php would contain the opening <html>, <head> and static content, and the footer.php would contain any extra static content and the closing </html> tag. So, my question is: Is this a good approach? I'm worried that spreading the <html> tags across multiple files is bad practice. If so, what is the right way to approach this kind of design?
Nope, your approach is wrong.
Here are main faults in your design:
You're assuming that header.php would be called on the every page call. That's wrong.
You're assuming that header.php will always be static. That's wrong.
You forgot to create a template for the page itself.
The main rule everyone have to learn by heart:
Not a single character has to be sent into browser, until all data gets ready.
Why?
it's 2011 today. AJAX era. What if your code will have to send JSONed data instead of whole HTML page?
there is a thing called HTTP header. Sometimes we have to send them. And it's gets impossible if you already have your ornate HTML header sent.
it's for just 4-page site. Okay. Imagine you've got lucky and got a request for another 4-page site. You will have to change only templates and don't touch engine files. That's really great benefit.
Imagine you're going to make a custom <title> tag for your pages, based on the page content. Isn't it extremely common thing? But you can't make it without using templates.
So, you have to have one common site template containing header and footer and also dedicated templates for the every php script.
An example layout is going to be like this:
.1. page itself.
it outputs nothing but only gather required data and calls a template:
<?php
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "template.php";
?>
.2. template.php which is your main site template,
consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<?php include $tpl ?>
</div>
</body>
</html>
.3. and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<?php foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
<ul>
easy, clean and maintainable.
In building off of Your Common Sense's answer, there's not a good reason to have 2 files for every page. You can easily combine your template (YCS called this .tpl.php) and your actual page into one file.
First, start off with a class that you can expand as your template needs expand:
<?php
#lib/PageTemplate.php
class PageTemplate {
public $PageTitle;
public $ContentHead;
public $ContentBody;
}
Then, make your layout:
<?php
# layout.php
require_once('lib/PageTemplate.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<title><?php if(isset($TPL->PageTitle)) { echo $TPL->PageTitle; } ?></title>
<?php if(isset($TPL->ContentHead)) { include $TPL->ContentHead; } ?>
</head>
<body>
<div id="content">
<?php if(isset($TPL->ContentBody)) { include $TPL->ContentBody; } ?>
</div>
</body>
</html>
And finally, add your page with the body content:
<?php
#Hello.php
require_once('lib/PageTemplate.php');
# trick to execute 1st time, but not 2nd so you don't have an inf loop
if (!isset($TPL)) {
$TPL = new PageTemplate();
$TPL->PageTitle = "My Title";
$TPL->ContentBody = __FILE__;
include "layout.php";
exit;
}
?>
<p><?php echo "Hello!"; ?></p>
This is a basic approach but, yeah, it does work :) I sure would bother with a lot of templating and OOP but you are definitely on the right path
As i can't comment anymore, then i will answer here ;) If he need a custom title then he needs some more advanced functions. So, as i told, this is a basic approach. But in the end, if he really have a static header/footer, and really use them everywhere, well, yes, this is a good way to go.
So ofc you could bother with some advanced headers with parameters you could feed on each page. You could go on a whole MVC stuff. In the end just tell him to use a pre-made framework and stop bothering. How could he learn if you don't let him do some trial and error ?
index.php -- includes header, footer, and content based on REQUEST variable.
header.php -- header content
footer.php -- footer content
content1.php, content2.php, etc.
index.php:
<?php
include ('header.php');
// VERY IMPORTANT - do not use the GET variable directly like this
// make sure to filter it through a white-list
include(basename($_GET['page']).'.php');
include ('footer.php');
?>
if you want the URL to go www.domain.com/pagename where the page you're trying to load into index.php is "pagename", use HTACCESS and do some URL Rewriting: http://corz.org/serv/tricks/htaccess2.php

php website one page for design

I'm done creating a php website that has 6 pages, and the structure of the pages is the same for each one of them, the only thing that changes is the content, so is the same header, same design and same footer, the only thing that changes like I said before is the content itself.
so i was thinking instead of having many pages, I could have only one design page, and change only the content, what do you recommend?,and how do I do that?, also im not planning installing anything like Typo3, wordpress, joomla or whatever in my server, so I want something i could do using php idk. thank you!
Simplest solution is to create separate files.
header.php
footer.php
menu.php
In header.php put your code from header
<?php ?>
<HTML>
<HEAD>
</HEAD>
<BODY>
...
<? ?>
Same goes for footer and menu files.
Then you can use it by including them.
Your index.php could look like following.
<?php
include("header.php");
include("menu.php");
?>
<h1> This is my content </h1>
<?php
include("footer.php");
?>
This is the easiest option I think for someone who doesn't want to spend using templates, CMS etc. Also you can create function called header that takes $title and changes title of your window. Up to you.
Sounds like you want AJAX. Use prototype. You can make one page, and then use prototype to swap out the content (which could include a PHP page) based on user clicks.
Simple and easy solution:
create footer.php and header.php
and in the header.php you can have something like this:
<?php function top_header($title) { ?>
<html>
<head>
<title> <?php echo $title ?> </title>
</head>
<body>
<?php } ?>
footer.php
<?php function footer() { ?>
</body>
</html>
<?php } ?>
Your index.php could look this:
<?php
include("header.php");
include("footer.php");
top_header("Title of the page");
?>
Hello World!
<?php footer(); ?>

HTML tags question

Something basic that i don't understand:
I have header.php with navigation bar for my site. Inside it, there's a <head>...</head> section.
Now, in each other page of my site, I'm using require_once 'header.php' so that each page will show the navigation bar. But, I need also specific <head>...</head> sections to the different page.
For example, in page customers.php, I'm using <script>...</script> to include the jQuery library. I don't need to include it in other pages.
Now, searching the web I see that multiple head tags is wrong syntax.
So, how can anyone:
avoid multiple "head" tags
WHILE
separating his work to different PHP files and including them ?
You have to change your page structure and employ templates.
Instead of loading header at the top of the code, you have to do it at the bottom!
And page code should output not a word, but collect all data in variables.
And only after that output can be started by calling template.
A example layout is going to be like this:
First. page itself.
it outputs nothing but only gather required data and calls a template:
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.php";
include "template.php";
?>
Next, template.php which is your main site template, consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
And, finally, links.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
easy, clean and maintainable.
there are many advantages in such approach:
as requested, you can populate header with actual page-relevant data.
HTTP headers can be sent as well, before any output. It includes cookies, sessions, cache-control and many more.
it's 2011 today. AJAX era. You may wish change your code to return JSONed data instead of whole HTML page. It's going to be easy using such layout.
Imagine you're going to create very similar site with just different design. You will have to change only templates and don't touch engine files. That's really great advantage of using templates.
Here are some simple ways you can look at.
You can have jQuery on the pages
that don't need it; once it's
downloaded it will be cached so it
still wont use more bandwidth.
You can move out the closing </head>
tag from header.php and close the
<head> tag in the page that's including
header.php.
You can include javascript anywhere
on a page, not only in the header.
You can also do something like this.
Before you do require_once 'header.php'; you put a variable called $jquery = true;
In your header.php file you check if $jquery is set to true, if it is, you include jQuery.
in header.php
you can type like this
<head>
<?php echo $script; ?>
</head>
then in your customers.php
you can first assign the variable
$script = '<script>...</script>'
then
require_once 'header.php'
One possible solution.
You create a global variable before including header.php.
You test this variable in header.php.
If it is true, You print script or something. Something like this:
<!-- Fragment of header.php -->
<?php if ($i_want_jquery): ?>
<script ...>
...
</script>
<?php endif; ?>
On the other hand, a template may be a better solution.

PHP - Use H1 Tags as Page Title

I just started with php. I have a pretty simple site with header and footer includes and the content in between.
Right now, I have each page getting the title with a variable, like so:
<?php $title = "My Company - New Products"; ?>
However, instead of having that on each page, in the header include, I'd just like to have the title be a standard "My Company - " and then have it pick up each page's H1 tag.
This seems simple, but all my search results have been specific to various CMS's.
Thanks a lot.
Why not define $title and then reference it more than once in the header?
Main page:
<?php
$title = "New Products";
require "header.php";
?>
<p>Rest of page...
Header.php:
<title>My Company - <?php echo htmlentities($title) ?></title>
<h1><?php echo htmlentities($title) ?></h1>
First, PHP has nothing to do with your page's H1 tag or whatever HTML tag, it should just generate a bunch of text, which happen to be a complete HTML document (or not depending upon you...)
You should probably look at templating mechanisms for PHP. Then, you can separate the logic necessary to generate the page content from the presention of this content as HTML. There are template engines like Smarty available, but many people will argue that PHP itself can be perfectly used as a template engine.
The easiest way to use PHP as a template engine is as described by jleedev. The PHP file as requested by the user generates variables (with the content of the page) and shouldn't contain any piece of HTML code (not even inside string variables). It then includes one or more template files, which use this variables to generate all HTML output without changing or computing any data.
I know this question is over a decade old, but here's what I use in 2022.
This will set the page title to the first H1 tag found on the page. If there are no tags, it will use the default title passed to it.
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo get_h1_title('My Company','Default Title if no H1'); ?></title>
</head>
<body>
<h1>H1 Title for this page</h1>
<p>Text for this page</p>
</body>
</html>
<?php
function get_h1_title ($prefix, $default_title)
{
$auto_title = $default_title;
$html = file_get_contents ($_SERVER['SCRIPT_FILENAME']);
if (!empty($html))
{
// Disable errors - DOMDocument doesn't handle any html5 we might use
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
// Get embedded h1 title if available
$header1s = $dom->getElementsByTagName('h1');
if (count($header1s))
{
$auto_title = $header1s[0]->nodeValue;
}
}
return $prefix . ' - ' . $auto_title;
}
?>
If on a given page you don't want the existing H1, just include a non-display H1 with the title you do want:
<body>
<h1 style="display:none">H1 that becomes page title but not displayed</h1>
<h1>H1 Title for this page</h1>
<p>Text for this page</p>
</body>
I agree with jleedev, but I use require() instead of include.
And don't use the shorthand opening php tag (<?)!

WebDesign: Header file, but with custom Page titles?

I've been using headers to create templates for websites.
It's easy, and very convenient for debugging.
I now face the problem of using head BUT with custom page titles.
If this is my header.php >
<html>
<head>
<title> My Site : ??? </html>
</head>
<body>
</body>
</html>
I need ??? to be replaced for every page.
Is this possible? If so, how? Thank you. : )
Not knowing more about your file inclusion scheme, the simplest way would be:
page2.php
<?php
$pageTitle = 'Page 2';
include 'header.php';
?>
<div>My content</div>
<?php include 'footer.php'; ?>
header.php
<html>
<head>
<title> My Site : <?php echo $pageTitle ?> </title>
</head>
<body>
footer.php
</body>
</html>
webbiedave's answer is perfectly fine, but in the long run, you should really learn to use either a decent template language (Smarty, Twig), or a PHP framework that has it's own templating. Kohana and Codeigniter are both pretty easy to get into.
If i were to add some code before including the header, will it help?
<?php
$currentPage = "Random Page Title";
include "header.php";
?>
And then use the value in header.php so print the page title?
you could query a DB for the title of a page and then print it using php :)
Edit:
Looking back at the problem , depending on how you have your website designed this may not be the simplest solution. But if you are already using some sort of ID system this should be easy.
Yes, it will help definitely. But you need to do a little customization.
First of all, make sure that you connect to the database, if you want to query / fetch data from database. For this to happen, include the "config.php" page at the very beginning of the script, in which your database connection logic will be present.
Then, write your query to fetch data from that database, and assign that value to the required variable for using it in the header page.
Lastly, include your "header.php" page.
For "config.php" page:-
Logic of Database Connection, like using of "mysql_connect()" & "mysql_select_db()" functions.
For "custom.php" page:-
<?php
include "config.php";
$sql = "SELECT pageTitle FROM db_table WHERE condition = 'something'";
$sql_exe = mysql_query($sql) or die("Error in Fetching Page Title");
if( mysql_num_rows($sql_exe) ) {
$currentPage = mysql_result($sql_exe, 0, 0);
}
else {
$currentPage = "Random Page Title";
}
mysql_free_result($sql_exe);
include "header.php";
?>
Also, if you want, you can always use some class for mysql connection & queries, to fetch data. But this is how it always work.
you can call javascript to change the title of the page dynamically, this is a better solution if you have a master file index.php that calls all other includes
You could also use something like this:
if you married up your php filenames with your page titles
you could use explode or str replace to make it more user friendly to replace commas or underscores for example.
<?php
echo basename($_SERVER['REQUEST_URI']);
?>
or
<?php
// my_page_title.php
$var=basename($_SERVER['REQUEST_URI']);
$pagetitle=str_replace("_"," ",$var);
// my page title
?>
<title> My Site : <?php echo $pagetitle; ?> </title>
Corrected 1 small error in Webbiedave's header.php entry
</html> should be </title>
<html>
<head>
<title> My Site : <?php echo $pageTitle ?> </title>
</head>
<body>

Categories