Is it bad to include header and footer as a template? - php

I was wondering if it's the right thing to include the tags like etc via another page.
What I mean by that is:
<?php include_once("header.php")?>
The content for each individual page
<?php include_once("footer.php")?>
Header.php contains:
<!DOCTYPE html>
<head>
<title>My Website</title>
</head>
<body>
Footer.php contains:
</body>
</html>
I am using it that way because when I have a lot of pages, it's a lot easier to just change one/two page(s). That way I spare time.
But the question is, is it bad to use a "template" style for my website?
( I saw some similair questions like this one but they didn't really answer my question, that's why I started a new topic - Sorry if it's wrong )

No problem with this I think - it's certainly better than duplicating the same content across multiple pages. Don't Repeat Yourself is a core tenant of programming, and this approach helps in that regard. The performance impact of the PHP includes is absolutely minimal and not worth worrying about, compared to advantage of easier maintenance.
You might be able to go further still though. Do you really need to repeat the includes on every page ? If all the pages have identical headers and footers, then you could make just one page that has them, and an area for dynamic content in the middle instead (this is the approach ASP.NET takes).

No, this is great. You will actually find there are more and more things you would like to move into included files, for example the sidebar for your website could be in its own file. This is exactly what PHP what made for, to allow for easier maintenance of your website.

Any PHP will be slower than only HTML. For example people use cacheing plugins for wordpress sites, so just HTML will be requested and the php server wont have to work as hard, and the page will be quicker. But the benefits of using PHP clearly outweigh this with the popularity of wordpress.
All php calls are made once, so multiple calls of php is not like multiple calls for css files or JavaScript.
As the site grows you will be happy to make one change that will affect all pages, rather than have to change each page. A simple example is a seasonal greeting in the header. Simple to ad and take away with your template. not so without. And that is before the more obvious link changes.

This is a good direction, just don't repeat yourself. Anyway, to get some more robustness from this templating idea you can try to take a look on the following libraries:
Twig : http://twig.sensiolabs.org
Smarty: http://www.smarty.net

Related

How to include a site-wide banner?

I realize this question is similar to this one but there didn't seem to be a definitive answer there. Currently I'm using <?php include "banner.html"; ?> but in order for this to work I need to change the ext of ALL pages to .php instead of .html.
I don't think this is really best practice. I'd prefer to keep my basic webpages as html files and reserve php files for server-side logic - isn't that the way it's supposed to be??
The banner should be displayed at the top of each page by default as soon as the page loads, so from what I've read jquery.load() is not appropriate as that should typically be triggered by user input. This is not an ASP.NET project so master pages is not an option. Also heard about HTML templating but after googling it I walked away more confused than ever.
I don't think this is really best practice.
It's fine, especially for small sites.
I'd prefer to keep my basic webpages as html files and reserve php files for server-side logic - isn't that the way it's supposed to be??
Keeping business logic and view logic apart is a good idea, but you don't need to go so far as to ban .php extensions on files that don't include business logic.
You might want to investigate the MVC pattern and the approaches taken by frameworks such as CodeIgniter or CakePHP if you want to see how other people keep their logic and HTML separate.
Either go ahead and convert the files to .php (totally fine practice), or use file_get_contents rather than include to get the HTML content:
<?php echo file_get_contents('banner.html'); ?>

Any problem if i will have only index.php instead of

i am trying to create a website, a dynamic one.
i wanted to know if is any problem if i will not divide the index.php file, so it will have the header , footer, sidebar etc, in one file. is any thing wrong here? So instead having, header.php, index.php, footer.php, sidebar.php, i will create only index.php..
need some suggestions from experts please
Thank you for reading this post.
absolutely nothing wrong. well. at the start.
you'll have issues with maintainability of that single file later when it gets bit. if you're planning to grow big.
No there is nothing wrong in that approach, it might be a pain to maintain though.
It's almost always a good idea to split things up this. My typical "simple" site layout has a header, a footer, and a body, each with its own files. It's rare for more than a couple pages to have different headers/footers, so almost every page ends up looking like:
<?php include('header.inc'); ?>
body goes here
<?php include('footer.inc'); ?>
And the header/footer files boil down to <html><body> and </body></html> respectively (with all the usual css/javascript/meta/headers, etc... of course).
Nothing wrong with keeping everything in a single file, but then you'd have to hard-code your menus/sidebars/footers/headers/etc... into every PHP file.
You need not any additional files.
This files are used only for easy edit, more obvious struct and having main code in different pages
I think it's great. Since your PHP-processor only needs to interpretet 1 file (instead of 4), it'll probably go a lot faster (when you are not using any OP code compiler).
Segregating your code is good practice as it helps prevent duplicate code. Say you want page2.php and you need the same header, footer, sidebar, etc. Are you going to copy/paste in that code? Just make your template views like they're supposed to and piece together your structure for optimal code redundancy avoidance.
If you NEVER plan on scaling this project, one page is fine.
While there is nothing wrong theoretically, this is by definition a bad practice.
By separating functional / organisational wholes into different files / classes / modules, you achieve decoupling and get a larger control level over your application, it will be much easier to maintain, you wont have to harcode and copy/paste much etc...
Why would you want to put all of your code into a single file?

What architecture should I use for writing my first dynamic website in PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I just want to build my first dynamic Website. I want to use PHP, MYSQL, AJAX, HTML, CSS
I have some beginner Questions:
Should the Header and Navigation Bar excluded in a header.php and print out with echo?
Should the design tags in the echo in php (like: <a>1 Test test</a>) or only return the the data
Is there a good example for making dynamic websites?
My main problem is that i don't know how to make a clear structure. Where to make the right design (print out in the php ?)
If it is really your first website, I'd actually recommend using nothing in terms of frameworks. This buys you some time to get comfortable with HTML/CSS, SQL and PHP, without overloading you with higher-level principles such as MVC (model/view/controller) and others. I'm mostly concerned that starting with a framework right away makes the learning curve to steep, and skips over things such as getting comfortable with the programming language you'll be using.
You'll eventually make a mess with way, but this will only make you appreciate the frameworks more; you can then make the transition to using a framework such as CodeIgniter, Symfony or CakePHP (or others, because there's a whole bunch more).
Other frameworks that I really like working with are Play! for Java, and Rails for Ruby. Since you stated you're a beginner, you might consider these as well.
Well, to answer all your questions at once.
The only technology you need is template.
Template is a typical PHP script, however, consists mostly of pure HTML, with some PHP code only to display dynamically generated data.
Create a main site template contains both header and navigation bar and footer everything else excluding actual page content.
Then create separate pages ("sections" of your site: news.php, links.php, etc.)
But make every page of 2 parts: getting data part and displaying data part.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors - it's time to include a main template.
A typical script may look like
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<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 links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.
Yes, I do recommend you include header and navbar scripts from another file.. where you can maintain them independently. I think that is pretty important.
I recommend you echo/print html from php, rather than insert php into html (easier when doing things like parsing $_GET/$_POST etc)
I recommend that you create a template, and another script which has functions that print (or echo) the html tags, header, footer, title bar, navbar etc. Just include the script with the functions and all your pages can have the following structure:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION,etc
if needed */
print_html_pre_content();
print '<p>Hello, world! or other content.</p>';
print_html_post_content();
?>
I have found this to be pretty clean, and it is easy to add functionality when you get to messing around with $_GET, $_POST and $_SESSION, etc.
I'd suggest to use some template system (Smarty would be good).
It does not really matter where do you put your header and navigation bar at first glance. When do you need to exclude Navigation bar and store it separately? When you want to have ability to include different nav. bars in different parts of your website.
For example I have a website with several subdomains: about.website.dev, special.website.dev and, let's say, terms.website.dev
At about.website.dev my navigation bar's entries will be: "Who I am", "What do I do", "How cool am I"; at special.website.dev: "Goods", "Solutions", "Tips" , etc.
Your navigation bar's template is the same: just a loop though all entries, but content differs. In this case you separate navigation bar from header. If you don't use templates, you just create three files (in this case): about.nav.php, special.nav.php and terms.nav.php and then you just include appropriate navigation bar.
If your nav. bar is all the same everywhere on your website, you can store it in header.php. Once you need to separate, it will not be difficult, but still I'd suggest to use templates though just to get used to "proper website development".
Take a look at different templating systems like Smarty or Savant. I, personally, like Django's (python) templating system most. And get used to separate your view and business logic.
IMHO, you would be better off having a look at a php-based web application framework. such as the list at http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
Even though it may be a little more to learn upfront (the framework as well as php), they all have solid enough structures to develop dynamic websites with. Find one that is light enough and has good tutorials and you'll find yourself learning the php language along the way. I believe this will be easier than just using raw php at the beginning stage.
When you know more you can then make a judgement call on which frameworks you prefer and suit your needs or coding style or even revert back to raw php.
If you want a good book on the subject, try
MySQL/PHP Database Applications by Brad Bulger, Jay Greenspan and David Wall
What you are asking is pretty much a matter of taste. The more complex your application will be, the more work should go into an elaborate and maintainable structure.
My opinion is: Learn the basics first and then look at frameworks. It makes it a lot easier if you understand what happens under the hood.
Try Agile Toolkit, probably the easiest PHP UI framework to get started with designed for web software.
You'll step over many problems. http://agiletoolkit.org
Depending of the choice of framework/plain PHP, you should do it in accordance with their practices. For instance in Agile Toolkit you use templates, so you put your header and footer into templates/jui/shared.html file. It's explained in the first screencast.
If you reinvent the wheel and go ahead with plain PHP, then you should do better do include 'header.php'; . Good framework lets you NOT learn about inner workings of web software. Bad framework needs you to know everything anyway.
There's a lot of good answers here already - but just to add....
Do split functionality into separate include files - and use a consistent way of locating these files.
Do find a good PHP coding style and stick to it. e.g. horde, PEAR
Don't have code or HTML executed inline in include files - it should only do something when you specifically invoke it from your controlling script.
If you are including files which generate HTML, make sure they provide functionality for closing any tags they open. i.e. not just a 'header.php'
Since CSS and Javascript files should not be directly declared outside the HEAD of the HTML document do look at ways by which invoked functionality can add these into an existing HTML document - one obvious solution is to use a templating system combined with output buffering but you can also inject additional JS and CSS files into the HEAD section later in the document by using javascript.
Use MVC - http://www.yiiframework.com/doc/guide/1.1/en/basics.mvc
See Yii-framework http://yiiframework.com, it has all you need :)

Idiomatic PHP web page creation

My PHP experience is rather limited. I've just inherited some stuff that looks odd to me, and I'd like to know if this is a standard way to do things. The page which shows up in the browser location (e.g. www.example.com/example_page) has something like:
<?
$title = "Page Title";
$meta = "Some metadata";
require("pageheader.inc");
?>
<!-- Content -->
Then pageheader.inc has stuff like:
<?
#$title = ($title) ? $title : "";
#$meta = ($meta) ? $meta : "";
?>
<html>
<head>
<title><?=$title?></title
</head>
<!-- and so forth -->
Maybe others find this style useful, but it confuses me. I suppose this could be a step toward a rudimentary content management system, but the way it works here I'd think it adds to the processing the server has to do without reducing the load on the web developer enough to make it worth the effort.
So, is this a normal way to create pages with PHP? Or should I pull all this in favor of a better approach?
Also, I know that "<?" (vs. "<?php" ) is undesirable; I'm just reproducing what is in the code.
Well, it's certainly not an invalid way to do it - but it might be a little cumbersome to read and maintain. I wouldn't say there's a "normal" way to do anything like this in PHP. At the end of the day, you're outputting variables into HTML - so there aren't a variety of options without using a dedicated templating engine (and/or heading towards a more MVC-based approach, as mentioned by ryeguy).
My suggestion: if it doesn't suit your preferred style, change it. The most important thing, if you're going to be developing and maintaining it, is that you can work with it comfortably, and efficiently.
It's kind of on the right track towards MVC. MVC is all about separation of concerns. The idea here is that the first snippet sets values, and then pageheader.inc outputs them. This keeps logic out of the view.
It's done very sloppily.
PHP is a very fragmented community with no "standard" way of doing things. That said, it appears the pageheader.inc example you posted can be simplified. The code at the top is doing you no good. This alone would suffice:
<html>
<head>
<title><?=#$title?></title>
</head>
If you're looking for some direction on architecture and best practices, I'd highly recommend checking out a popular PHP framework like Codeigniter or Kohana.
There are essentially two approaches you can use, and they are inverses of each other. You have an example of one approach, where each page has its own content is responsible for including the header, footer, and other common data. There is nothing particularly wrong with this approach. The second approach is to have a single page that is responsible for including the header, footer, and content. This is far more common applications using popular PHP frameworks.
I've used that style a lot on simple sites like 5-10 page brochure-ware sites where I want some centralised code e.g creating menus and page headers from a few variables, but don't want a full-blown MVC structure as it's be overkill.

reducing duplication in static HTML pages

I have a website which consists of a bunch of static HTML pages. Obviously there's a lot of duplication among these (header, menu, etc). The hosting company I plan to use supports PHP, which I know nothing about. Presumably PHP provides some sort of #include mechanism, but what changes to I need to make to my HTML pages to use it?
For example, suppose I have a page like this
index.html
<html>
<head></head>
<body>
<h1>My Common Header</h1>
</body>
</html>
Obviously I need to move the common part into it's own file:
header.html
<h1>My Common Header</h1>
Given the example above (and assuming all files are in the same directory):
What do I add within the body tag to get header.html included?
Do I need to rename index.html or add some special tags to indicate that it's a .php file?
Do I need to make any changes to header.html?
Update: I want to emphasise that my objective here is simply to find the lowest-friction means of reducing duplication among static HTML files. I'm a bit reluctant to go down the server side includes route because I don't yet know what type of server (IIS/Apache) I'll be hosting the files on, and whether includes will be turned on or off. I was drawn towards PHP only because it is about the only thing I can presume will be available that will be able to do the job. Thanks for the responses.
Thanks,
Donal
You are looking for include (or one of its derivative such as include_once, require, require_once):
header.php
<h1>My Common Header</h1>
index.php
<html>
<head></head>
<body>
<?php include('header.php'); ?>
</body>
</html>
And so on, for your footer for example.
You don't need to use PHP to get this functionality, and it's generally a bad idea to do so due to potential security concerns. Essentially, you're swatting a gnat with a nuclear bomb. If you're not using a dynamic language, then you're looking for server side includes.
In IIS, for instance:
<!--#include virtual="file.inc"-->
Be aware that you often have to configure the server to utilize them, as this feature is often turned off by default. Both IIS and Apache support server side includes, but they use different configurations.
You can find more information here:
Server Side Includes
EDIT: I don't mean that it's a bad idea to use PHP, just using PHP solely for including other files. It creates a larger attack surface by bringing PHP into the mix when it's not needed, thus the potential for security issues when the functionality of PHP is not required.
EDIT2: I think it's a bad idea to assume you won't be a target because of your size, and thus you can ignore security. Most sites are compromised by automated worms and turned into malware hosts, spam zombies, or pirated software/media servers. Apart from the fact that you might end up being involved with infecting others, your site can become blacklisted and it can cost you real money in bandwidth overage charges. We're talking hundreds or thousands of dollars.
Just because you're a small site doesn't make you any less of a target. Just being on the internet makes you a target.
Forget doing it on the server altogether.
If all you really want to do is maintain some static pages -- and don't anticipate ever having to really use PHP -- I'd just do it with Dreamweaver, which will allow you create and manage templates and variable content on your end.
No includes needed. No templating engine needed. (These would be overkill for what you are trying to accomplish.)
You should first change the file extensions of index and header to be .php, then you can do:
<html>
<head></head>
<body>
<? include 'header.php'; ?>
</body>
</html>
And your header.php file just has
<h1>My Common Header</h1>
While you can just use the "include", "require", or "require_once" directives to include things in one page, you might have better luck with a template engine like Smarty
While using an include file for the header is a solution I went a different route when I faced the problem several years back: I wanted all pages to use the same layout (which I assume is rather common ;-). Thus, as I only wanted to change the content of the page I made the page content the file that gets included and have a master template file that includes header and footer. For setting the page to be included I resorted to creating quite small php scripts that only set a variable that holds the page to get included. In some cases the page can also get named by a GET parameter. Of course this requires proper validation of that parameter. In the long run I don't need to worry about the HTML itself anymore -- all I do is write small snippets (which should be complete for themselves of course) that get included.
A possibly even better solution would be to use an existing template framework. Due to the contraints I had back then I wasn't able to do so, but I would do it when facing the same issue again.
Back in the day, I used SSIs (the "<!--#include virtual="file.inc"-->" method described above by Mystere Man) quite a bit for static HTML pages and I would definitely recommend using that.
However if you want to eliminate any uncertainty about whether support for that will be enabled on the server, you could develop your separate files locally and merge them into the resulting files before uploading to your server. Dreamweaver, for example, supports doing this in a seamless fashion.
Or you could do it yourself with a rather simple script in your language of choice by doing simple string replacement on markers in the files, replacing {{{include-header}}} with the contents of a "header.html" file and so on.
Edit
Oops! Somehow I didn't see Clayton's post with the same note about Dreamweaver.
OK this is a semi-programming related question only.
PHP does have include(), which is really easy to use, but it doesn't contribute to future maintainability. I wouldn't recommend it, especially for big sites.
I'm a pro-frameworks. I've used CodeIgniter, CakePHP and even Smarty template engine. If you are serious about PHP, do consider CakePHP. There's this "layouts" concept where you frame your header, footer, css, javascript outside of the main content; e.g. for the "about us" page, your content would be something like:
This is an about us page that tells you a whole bunch of stuff about us...
CakePHP takes this this content, and wraps your layout around it:
header
css
javascript
This is an about us page that tells you a whole bunch of stuff about us...
footer

Categories