I am wondering how would I include various elements (header, footer, nav), in one php file to be included on various pages, rather than creating multiple php files to be called separately?
In my includes file I have the following code:
<?php
echo '<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> Carnival, Residue, Maudlin</span>.</h1>';
?>
Outputting onto an html page that is running php I have:
<?php include('php-includes/current-elements.php');?>
Is there a way to include a particular div or class, something other than the entire file itself?
I just didnt want to create a separate php include file for every little element that i want to include on the same page.
The code below is what I had within the same include file to call a different element to be displayed on another page.
<?php
function elements ()
{
echo'<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> TESTING</span>.</h1>';
elements();
}
?>
Any help would be great!
It sounds like you are trying to avoid templates. The basic idea is to define a separate file for each of head, footer, nav and include those from your content template.
head.php
<!doctype html> <html> ...
nav.php
<body> <a href=..> page1 </a> <a href=..> page2 </a> <a href=..> page3 </a>
foot.php
</body> </html>
And to create a complete page, you would do:
<?php
include 'head.php';
include 'nav.php'
An article about prune juice.
include 'foot.php';
?>
Now, if I understand correctly, you want to include only one file and be able to generate the various elements (head, nav, whathaveyou). You could do this by wrapping the include statements in functions:
ubertemplate
<?php
function head() { include 'head.php'; }
function nav() { include 'nav.php'; }
function randomElement() { ?>
An article about prune juice. <?php
}
function totalymisguideddynamiccontents() {
echo "<div> foobar <span> moo </span></div>"
}
function() { include 'foot.php'; }
?>
..then in your final page, call these functions:
uberpage
<?php
include 'ubertemplate.php';
?>
<?php head() ?>
<script src=superlib.js></src>
<?php nav() ?>
Yomama so big when she wears a yellow coat people yell TAXI!.
<?php foot() ?>
Finally, if I understand correctly and you think the uberpage approach seems like a good idea, ...then you should probably try it out. That may well be the only way to realize that it is flawed. I don't mean to mock your idea, but there are better ways to approach templates and the first way, the one you are trying to avoid, is cleaner (but that's only my opinion).
For a better way, look at twig templates or do some more research and find a framework that suits your needs.
Related
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
I've been searching around for a good hour or so and haven't really found anything to answer my question.
The thing is, I understand how to make a page and do:
index.php
<?php
include 'head.php';
include 'nav.php';
include 'footer.php';
?>
But in my nav.php, I'm not sure how the works, and how to include different content pages within my index.php like: contact.php, registration.php, etc.
I don't know how make it so that if I were to click the "contact" navigation link for example, only the content would change, and I wouldn't have to make a whole separate HTML file like so: Contact
Hopefully I explained it good enough. If anyone can give me a reference or explain how to do this, I would greatly appreciate it. Thank you guys.
I quoted your answer, this is the line
I don't know how make it so that if I were to click the "contact"
navigation link for example, only the content would change, and I
wouldn't have to make a whole separate HTML file like so:
<a> href="bla.html">Contact</a>
it's not the way it should be, what i get from your question is, you wanted a full page is all the same
<?php include 'head.php'; include 'nav.php';
and only this content should be change, not the head, not the nav, nor footer.
include 'footer.php'; ?>
am I correct?
if it is what you wanted, you should place a php file whatever the name is, index.php would be better. and the link it self should be called with something that php can get it.
Contact US
and in your index.php, you also create a condition if else would be easier.
if($_GET['contact']){
place your html /php here
}
else if($_GET['about']){
place your html /php here
}
else{
include 'index.php';
exit();
}
I suggest you not to do this, everyone is now can do the code, but not the code architecture .
wish it help you to understand.
You need to use different views. I believe you are looking for a way to change the view using php. One way is to add the page id in the url like 'www.myweb.com/index.php?page=contact' and receive it as a $_GET['page']. I think this is the simplest way to change the view using php. And this is the index.php, put all the view file in the views folder.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
include 'head.php';
include 'nav.php';
switch($_GET["page"]){
case 'contact':
include 'views/contact.php';
break;
case 'registration':
include 'views/registration.php';
break;
case 'chat':
include 'views/chat.php';
break;
}
include 'footer.php';
?>
</body>
</html>
this would be your nav.php;
<ul>
<li> Contact </li>
<li> registration </li>
</ul>
I am new to PHP and programming in general and hope someone can help me with this.
I am working on building a website where the code for each page is saved in a separate file.
Now I have a couple of code snippets that I want to use on different pages but not on all of them.
My current approach is that I paste them on every file that uses them which duplicates code and therefore supposedly is not good practice.
On the other hand when I use snippets on all pages I have removed them from the single files and store them as separate includes files using PHP's include or require in order to include them on a page, e.g. for the header, the footer and the menu etc. - example:
require_once("includes/header.php");
This works well and I was wondering if there is a similar way I can include the other code snippets as well BUT without having to save each of them as a separate file.
Is there a way for example that I could use functions for this or is there some other common practice ?
Example (just to show what I mean):
<?php
// example of what I would like to include on different pages
echo "<button type="button" class="class1" id="btn1">Button 1</button><br />
<button type="button" class="class2" id="btn1">Button 2</button><br />
<button type="button" class="class3" id="btn1">Button 3</button><br />";
?>
The pieces to insert could be anything but usually they are some small PHP / HTML snippets, like a set of buttons or a div or a dropdown etc.
Make the code snippets inside a function so you can call it on any other page by including the same page everytime.
Let's say we have an index.php page, and we have a test.php that have this code (that we want to include on the index page):
<?php
function hello(){
echo 'Hello World!';
}
hello(); //to print "hello world!" in this particular page
?>
Now, in the index.php page, we put:
<?php
include('test.php');
?>
<h1><?php hello(); ?></h1>
use a single index.php file to handle the rest
index.php
<?php
require_once 'header.php';
if(isset($_GET['page']){
switch($_GET['page']){
case "123":
require_once 'snippet1.php';
break;
case "1234":
require_once 'snippet2.php';
break;
default:
require_once 'notfound.php';
}
}
require_once 'footer.php';
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.
I know this is a basic PHP question, and I'm trying to learn the stuff. I very familiar with HTML, CSS and familiar with the CONCEPT of PHP, but not with specifics.
I have always partnered with a back end developer to accomplish this stuff and to set up wordpress sites, etc.
I'm building a very basic four or five page website (a showcase for the client's custom fishing rods: http://www.tuscaroratackle.com/index2.php). I want to call the page header (as in logo, navigation, etc., not as in the head element) dynamically from a php file, and same thing with the footer, so I don't have to rewrite all the markup on every page for these bits.
I don't intend to use a database for this site, I was just thinking I could call those two bits from another file, as you would in a wordpress setup with the header.php in the wp-content directory.
Is there an easy explanation on how to do this? (I get the basics, just looking for help on the more specific PHP calls that need to be made)
Or, if this is not an answer somebody could easy give, can you point me to a good resource to research it further?
Thx
You betcha - include and require -
using include
in your page:
<body>
<?php include 'header.php'; ?>
in your header.php
<div id="header">
<!-- content -->
<?php echo "run php stuff too"; ?>
</div>
would result in:
<body>
<div id="header">
<!-- content -->
run php stuff too
</div>
You should put the header html code in some file such as header.php and then include it with php like:
include ('header.php');
You should specify the correct path there, for example, if you put the header.php file in includes folder, you can include it like:
include ('inclues/header.php');
More Info:
http://php.net/include
Put in a separate file and use include, require or require_once.
Eg
require_once("path/to/myfile.php");
Look into PHP includes.
The way I normally do it is to create a file called includes.php with two functions header() and footer(), then call them on each page like such:
includes.php:
<?php
function header(){
echo '<div id="header">Welcome</div>';
}
function footer(){
echo '<div id="footer">Goodbye</div>';
}
?>
index.php:
<?php
include_once('includes.php');
header();
echo '<div id="content">Main page body</div>';
footer();
?>