I have the following code to include pages dynamically:
<div id="content">
<div id="aside">
...
</div>
<div id="main">
<?php
$page = (isset($_GET['page'])) ? sanitize($_GET['page']) : 'home';
if (!include 'pages/'.$page.'.php') require 'pages/404.php';
?>
</div>
</div>
As you can see, the #aside has static content.
I want to include a specific content for the #aside depending on the page selected. For example, if the user goes to 'Home' and 'About', I want the 'default' aside. But if the user goes to 'Documents' I want a 'Sections' aside.
I know I can just include each aside from every page, but that's not effective. I also don't want the user to be hable to set the aside as the main content, so they have to be in different folders or something.
I'd like to know an effective and not so complicated way to do this.
Thanks for taking your time to read this.
You want to keep which sidebar goes on which page in a database, and then query that database for the correct sidebar to include.
A table structure may look like this:
Table sidebars: ID | path | name | more info on sidebar...
Table pages: ID | path | name | more info on page...
Table sidebars-to-pages: page_ID | sidebar_ID
This approach even allows you to place multiple sidebars on a specific page.
What if you did this?
<?php
ob_start();
$page = (isset($_GET['page'])) ? sanitize($_GET['page']) : 'home';
if (!include 'pages/'.$page.'.php') require 'pages/404.php';
$contents = ob_get_clean();
?>
<div id="content">
<div id="aside">
<?php include($aside); ?>
</div>
<div id="main">
<?php echo $contents; ?>
</div>
</div>
and $page.php would look like:
<?php $aside = "sidebars/default.php"; ?>
<p>HTML for #main<br />
goes here</p>
There are a few different ways to do this that are all more-or-less equal. I almost always use a config.php file for sites to hold whatever global information I want every page to have. At the top of every page, you just call
<?php
require_once('config.php');
?>
In that config.php file, you could have an array listing your page names and the file you want included for each page, as well as a function that returns the content, like so:
// this lets you call includes relative to the site root
set_include_path($_SERVER['DOCUMENT_ROOT']);
$defaultAsideContent = 'includes/default.php';
$asideContent = array(
'index.php' => 'includes/include-1.php',
'document.php' => 'includes/include-2.php'
);
function getAsideContent() {
global $asideContent;
global $defaultAsideContent;
$content = $defaultAsideContent;
// get the requested page
$pageFull = $_SERVER['REQUEST_URI'];
// strip URL variables
$pageParts = explode('?', $pageFull);
$page = $pageParts[0];
// loop throught the array and see if there is specific aside content for the page
foreach($asideContent as $key=>$value) {
if ($page == $key) {
$content = $asideContent[$key]);
}
}
include($content);
}
Lastly, wherever you want your aside content to show up, just do
<?php getAsideContent(); ?>
When you create a new page, if you want specific aside content, just edit your config file. Just FYI, didn't test this at all, probably has bugs, but you get the jist.
Thank you all for your answers and collaboration. Although none of the answers did exactly what I was looking for, they showed me other ways to approach this issue and guided me to decide what method to use.
I came up with what I think is the simpliest way to do this:
I set my folder structure as: pages/aside and pages/main
I set up an array($asides) with the aside files as the keys and the main content files as the values.
Then I check if the requested file exists in the main folder.
If it doesn't exist, I redirect the user to the 404 page. If it does exist, I loop through $asides to see which aside is asigned to that main content page.
If it doesn't belong to any of the establisged asides, then I include the default aside.
$asides = array(
'aside1' => array('page1', 'page2', 'page3', 'page4'),
'aside2' => array('page5', 'page6')
);
$page = (!empty($_GET['p'])) ? sanitize($_GET['p']) : 'page1';
if (file_exists("pages/main/{$page}.php")) {
foreach ($asides as $key => $value) {
if (in_array($page, $asides[$key])) {
$aside = $key;
break;
}
}
if (!isset($aside)) $aside = 'default';
?>
<div id="aside"><?php require "pages/aside/{$aside}.php"; ?></div>
<div id="main"><?php require "pages/main/{$page}.php"; ?></div>
<?php
} else {
header('Location: ?p=404');
}
The bounty goes to Madara Uchiha because in my opinion, his answer is simple an effective. Thanks again to all of you who helped me with this issue.
Related
Currently my site title looks like:
<title>My Site Title</title>
The above code is added on 'header.php' file, so every pages has the same page title.
I need to set different titles for different pages.
for example,
<title>
if 'contact.php' then title= 'Contact Us'
else if 'faq.php' then title= 'FAQ'
else if 'add.php' then title= 'Add'
else title= 'My Site Title'
</title>
somebody please help me!!
I guess contact.php include 'header.php';. Then something like this would work:
contact.php:
<?php
$title = 'Contact Us';
include 'header.php';
// your code
?>
header.php:
<?php
echo '<title>'.$title.'</title>';
Tip: have a look at template engines. I like smarty for example. Maybe someone will comment on this with some other examples ;)
Make a variable in your script called $page and use that variable in the template file.
Business logic for page Home, for example:
<?php
.
.
.
$page = 'Home';
render($page);
View logic page for Home:
.
.
.
<title>
<?php echo $page; ?>
</title>
.
.
.
This is just a concept, it is not a fully functional code.
Split your header in to 2 seperate php files, one before the title, and one after the title (this will work with other page specific data, see note at end of answer)
then the top of your pages should look like:
<?php include_once("inc/begin-head.inc");?>
<title>My Title</title>
<meta name="description" content="description"></meta>
<?php include_once("inc/end-head.inc");?>
There are some other solutions, such as make header a class and define variations to it, and then call a function to output the head completly
Please note, there are a LOT of other paged specific tags. Title, Meta Description, Canonical url link, meta keywords, open graph data .....
You can try like this and use basename($_SERVER['PHP_SELF']) and now lookup for the $title[key]
$title = array();
$title['home.php'] = 'My home page';
$title['Hello.php'] = 'My title';
I'd advice you to use an array with titles instead of a series of ifs (respectively a switch)
<?php
$file = basename($_SERVER['PHP_SELF']);
$titles = array(
'contact.php' => 'Contact Us',
'faq.php' => 'FAQ',
'add.php' => 'Add',
);
if(array_key_exists($file, $titles){
echo '<title>'.$titles[$file].'</title>';
}else{
echo '<title>Ny Site Title</title>';
}
?>
To add title dynamically , first set the following code in header.php file :
<title>
<?php
if(isset($title) && !empty($title)) {
echo $title;
} else {
echo "Default title tag";
}
?>
</title>
and set title in each page before including header as :
$title = "Your Title";
include 'header.php';
How I did this for anyone curious in the future...
I have a "pagetitles.php" page that contains this code:
$page_files=array(
"admin"=>"Admin Panel",
"profile"=>"Your Profile",
"billing"=>"Billing / Subscriptions",
"pricing"=>"Our Pricing",
"settings"=>"Your Settings",
"bugs"=>"Bug/Feature Tracker",
"search"=>"Search Results",
"clients"=>"My Clients");
if(isset($_GET['rq'])){
if(in_array($_GET['rq'],array_keys($page_files))) {
$pagetitle = $page_files[$_GET['rq']];
}
}
Then I include that file at the very top of my index.php page, and echo $pagetitle where I want the title to be. BUT this also requires another file to handle serving the specific pages, using a ?rq request
In my "page_dir.php" file, I have the following that handles ?rq= pages (ex: www.example.com?rq=home will load the home page, with the above page title that's inside of "home" array)
Here's the page_dir.php file:
$page_files=array(
"noaccess"=>"pages/noaccess.php",
"home"=>"pages/dashboard/home.php",
"lists"=>"pages/dashboard/lists.php"
);
if(isset($_GET['rq'])){
if(in_array($_GET['rq'],array_keys($page_files))) {
include $page_files[$_GET['rq']];
}else{
include $page_files['home'];
}}else{
include $page_files['home'];
}
This page_dir.php file, I put on the index page where I want main content to show up at... I then have each individual page with just the content (like home.php file is just home.php content without the navbar and footer)
On my index.php file, where I want the page title, I have this code:
if(isset($code_nav_title)){
echo $code_nav_title;
}elseif(isset($pagetitle)){
echo $pagetitle;
}else{
echo "Default Page Title Here";
}
the $code_nav_title lets me set the page title from form submissions if I want it to say "success" or "failed" :) the "default page title here" lets you set something to automatically show up if everything fails to show (like if you forgot to set the page title)
Hopefully this makes sense! It's saved me sooo many headaches and makes it easy for expansion/changes!
Basically I have some pages that I built for a website and all have the same layout. I was thinking that it is a waste to include all the code that is the same in all the files (wasted bandwidth, waste of time and so on). At first I thought about using frames but I didn't like them very much... I won't give up on them, I just started reading about them but anyway the solution that I really liked and felt like it fit me was I wrote an html file with all the basic layout that is present in every page and then I just wrote a php script in the main area as it is (the part of the page that differs) and depending on the $_GET[] value I include_once("page.php") where that file basically has html code and a little bit of php for some dynamic content that has to do with a database on the server. So it looks like this
<html>
<head>
<!-- css and jquery file -->
</head>
<body>
<div id='title'>
</div>
<div id='navigation'>
</div>
<div id='content' style='float:left'>
<?php
switch($_GET['id']) {
case '1': include_once('./pages/1.php');
case '2': include_once('./pages/2.php');
.......
}
?>
</div>
<div id='sidelinks'>
</div>
<div id='footer'>
</div>
<!-- various javascript files for events -->
</body>
</html>
However I am just a few months into php and though I read about include I am still not sure if it is bad practice, has any problems or dangers
That's ok and very normal. PHP includes can make managing common content across pages a simple process and thus make site maintenance easier. That's a good thing.
Common examples include:
Headers
Footers
Site Navigation
As John Conde said it's perfectly OK. I would enhance your script a little:
// use an array that holds your pages
$pages = array();
$pages[] = array(
'title' => 'Startpage',
'metaDescription' => 'Meta Description',
'include' => './pages/1.php',
// etc.
);
$pages[404] = array(
'title' => '404',
'metaDescription' => 'Meta Description',
'include' => './pages/1.php',
// etc.
);
$request = 0;
Than you can check:
if (isset($_GET['id']) {
$request = ( count($pages) > intval($_GET['id']) ? intval($_GET['id']) : 404 );
}
if (404 == $request) {
// send 404 headers
}
And afterwards you can use: print $pages[$request]['title']; to display an individual page title and you can include the requested file using require $pages[$request]['include']; and so on.
This is just written by heart - not tested and it could simply be improved. It's just an idea to go a little further.
It's OK with the way you are going. The only thing you should think about is how to handle HTTP 404 error in case when someone gives incorrect page id.
1- You must prevent any error in your page.
2- In your place I do not use switch
<?php
$pageid = $_GET['id'];
$errormsg = '';
if($pageid)
{
$file_to_call = './pages/' . $pageid . '.php';
if(is_file($file_to_call))
{
include_once($file_to_call);
}
else
{
$errormsg = "YOUR MESSAGE ERROR";
}
}
else
{
$errormsg = "YOUR ANOTHER MESSAGE ERROR";
}
echo $errormsg;
?>
The way you're doing it (by ID number rather than passing a filename) is OK, safer still would be to use file_get_contents, that way you're not importing a file as if it were some code.
Im developing a website and I am trying to a foreach include for my header which includes my navigation menu (the main topic here).
My code inside the header.php file for the navigation menu is here:
<!-- topmenu -->
<div class="menu-header">
<div class="container">
<ul class="top menu">
<?php
$nav = array("Home","About","Portfolio","Products","Services","Contact");
foreach($nav as $item){
if($item == $title){
echo "<li class='current-menu-ancestor parent'><a href='$item.php'>$item</a></li>";
}else{
echo "<li><a href='$item.php'>$item</a></li>"; }
}
?>
</ul>
</div>
</div>
<!--/ topmenu -->
You may notice that in the code is the condition if($item == $title). In my index.php I have included $title="Home"; which I intended to be taken and used in this if statement.
On my index.php page I have included this with the following code:
<?php
include("header.php");
$title = "Home";
?>
Can anyone tell me where I am going wrong?
Not an answer, but comments aren't suitable for formatted code. You might want to de-duplicate some of your HTML:
$class = '';
if($item == $title) {
$class = ' class"current-menu-ancestor parent"';
}
echo "<li{$class}><a href='$item.php'>$item</a></li>";
Duplicating HTML as you did can lead to maintenance problems later on, if you decide to change something in the menu structure and change only one of the copies of the menu html.
header.php can not look into the future. If you want the variable to be set in the include, you need to set it before:
<?php
$title = "Home";
include("header.php");
?>
So you basically just switched the lines.
Additionally I suggest that you enable error reporting to the highest level when you develop, as it will give you warning on common mistakes that can happen while typing code.
You can do this by adding the following two lines to the top of your script:
error_reporting(~0);
ini_set("display_errors", "1″);
or by changing your PHP configuration.
You need to set $title before including header.php!
i.e.
<?php
$title = "Home";
include("header.php");
?>
I have 7 different pages. All pages are the same considering the layout, but are different considering the content. The content is provided by a database, depending on what the users click on.
I figured out you have to pass the variable using the URL, and by so defining which content to load, right?
So, this is my menu-item:
<a id="menupag" class="item1" href="index.php?page=groups?group1">
This is my index:
<div class="content">
<?php
include_once ('content/'.$_GET['page'].'.php');
?>
</div>
But for some reason, when I click on the menu-item, this message appears:
Warning: include_once(content/groups?group1.php): failed to open stream: No such file or directory in httpd.www/new/index.php on line 32
What do I have to do to let php ignore the last part of the URL (this part is only used to define which data the database has to return) and just listen to the index.php?page=groups?
You pass parameters in URL in a bad way:
You should change it into:
<a id="menupag" class="item1" href="index.php?page=groups&group=group1">
so you will have in $_GET superglobal two values:
$_GET['page']; // value: groups
$_GET['group']; // value: group1
However using:
include_once ('content/'.$_GET['page'].'.php');
is totally unsafe. The better solution is:
$allow = array('groups', 'about', 'users');
$page = in_array($_GET['page'], $allow) ? $_GET['page'] : 'default';
include_once ('content/'.$page.'.php');
For security reasons you should have a whitelist so people can't include files you don't want them to include. You could use an array for this.
$validPages = array("groups", "home");
if (in_array($_GET['page'], $validPages)
{
$include = $_GET['page'];
}
else
{
$include = "home"; //Your default
}
<div class="content">
<?php
include_once ('content/'.$include.'.php');
?>
</div>
In answer to your question, your querystring looks invalid. Shouldn't it be index.php?page=groups&group=group1?
If not then you need to check for a question mark by doing:
$include = explode('?', $include);
$include = $include[0];
Not good way to use
<a id="menupag" class="item1" href="index.php?page=groups?group1">
Use like
<a id="menupag" class="item1" href="index.php?page=groups&varame=group1">
Otherwise
$page = array_shift(explode('?' ,$_GET['page']));
Or
$page = explode('?' ,$_GET['page']);
// use $page[0];
I am newbi to wordpress. I have created a website in wordpress which has totally 6 pages.
here 5 pages use the same header, but only one page has different header. So i how can how to create new header.
header.php(is used by all 5 pages): In this case is used "get_header();" in page.php to call the header.
home.php(to be used by home page). here is ther any possible way to access these new header
Please check the link
if link is www.test.com/home.php
then use
<?php if($_SERVER['REQUEST_URI'] == 'home.php') { ?>
<h1>Header for the Homepage</h1>
<?php } else { ?>
<h1>Header for other pages</h1>
<?php } ?>
There's different ways to do this. The easiest would be to use is_home() in header.php to check if the currently loaded page is the homepage. You could change the header.php to something like:
<?php if(is_home()) { ?>
<h1>Header for the Homepage</h1>
<?php } else { ?>
<h1>Header for other pages</h1>
<?php } ?>