How to determine what page called called the php include? - php

I am working on an established website which has many problems in it. I am trying to incorporate a new navbar that will be coded in a 'header.php' file. I want to call it in the index.php and other pages using <?php include('header.php') ?> but there are differences in the pages and it needs the header.php to be dynamic. I want the header.php to have some slight changes when called by a specific page. How can I dynamically change the header.php file depending on what page called it?
This is my code:
HEADER.PHP
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/angel-header.css">
<!-- RENAME THIS CSS FILE APPROPRIATELY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body class="m-price_update price_starway vb lang-en webp">
<header class="angelmod-site-header">
<div class="angelmod-wrapper">
<a href="#">
<img src="img/logo_sb.png" alt="Small Builders">
</a>
<nav class="angelmod-site-nav">
<ul class="angelmod-nav-list">
<li>Home
</li>
<li>Products
</li>
<li>Signup
</li>
<li>Login
</li>
</ul>
</nav>
<div class="angel-mod-navbtn">
<div class="angel-mod-navbtn-bars"></div>
<div class="angel-mod-navbtn-bars"></div>
<div class="angel-mod-navbtn-bars"></div>
</div>
</div>
<script src="js/angel-header.js"></script>
<!-- RENAME THIS JS FILE APPROPRIATELY -->
</header>
I have a products.php file that needs to change the body tag to: <body class="m-price_update price_starway vb lang-en webp"> right now the header.php only have <body>.
Please don't ask why the body differs from page to page, it's the previous dev's work and I am tasked to not change those.

Any variables defined in the file doing the including will be available in the included file. Just define a variable in the including file that identifies what needs to be done in the included file.
// products.php
$include_option = 'products';
include('header.php');
Then in the included file, refer to that variable at the appropriate place to conditionally do whatever needs to be done:
// header.php
...
<?php if ($include_option == 'products') { ?>
<body class="m-price_update price_starway vb lang-en webp">
<?php } else { ?>
<body class="something else">
<?php } ?>
...

Related

PHP/HTML structural way

I have a sample index.php page like this:
<?php
Define("_DEF",1);
require_once "database.php";
require_once "session.php";
require_once 'functions.php';
if (isset($_GET['logout'])) {
$session->logout();
} else if (isset($_GET['add'])) {
$addFlag = 1;
}
if(!$session->is_logged_in())
redirect_to("login.php");
?>
<html>
<header>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
</header>
<head>
<link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>
<meta charset="utf-8">
<title>Messaging Panel</title>
<link href="style_index.css" media="screen" rel="stylesheet" type="text/css" />
<link href="iconic.css" media="screen" rel="stylesheet" type="text/css" />
<script src="prefix-free.js"></script>
</head>
<body>
<div class="wrap">
<nav>
<ul class="menu">
<li><span class="iconic home"></span> Home</li>
<li><span class="iconic plus-alt"></span> New Message</li>
<li><span class="iconic mail"></span> List Messages</li>
<li><span class="iconic user"></span> Logout</li>
</ul>
<div class="clearfix"></div>
</nav>
</div>
<?php if (isset($addFlag) && $addFlag==1){ ?>
<h3>Add Message HTML Goes Here!</h3>
<?php }
</body>
</html>
I have several HTML forms for different action. E.g. when user calls index.php?add I want to display a custom form to add new message into my database. My current code as you can seed will be so complex if I'm goint to have several actions in my index.php and it will looks like a big if-else structure which be hard to debug. I want to know are there any structured method to have specific HTML for each situation and then include it based on PHP variables status? Currently I know I can call a function to display the form using echo HTML_TAGs , but are there any methods to have HTML form in seperate file and php functions bring it to HTML based on passed variables?
My main target is to have a structure of files for each situation (one for add record, one for list records , ...).
Note: Currently I don't know anything about jQuery. So I look for simple HTML+PHP solutions! :)
You can use require_once,require,include and include_once
Sample form
addForm.php
<form action="tosend.php">
<!-- Sample elements here -->
<input type="text" name=""/>
</form>
then in your php file where you want to include html file just use require_once or include_once
Sample
if(condition){
//condition is meet include the form
include_once('location/addForm.php');
}else{
include_once('includeAnotherForm.php');
}
You can have HTML elements in different files. Than you can require('file.ext') to display that page.
<?php
require(__DIR__.'/header.php');
if (isset($_REQUEST['page']) && file_exists(__DIR__."/pages/{$_REQUEST['page']}")) {
require(__DIR__."/pages/{$_REQUEST['page']}.php");
} else {
require(__DIR__."/pages/home.php");
}
require(__DIR__.'footer.php');
?>
Personally, since you already have separate files for session.php, etc. I'd probably write a view.php as well, with the following setup:
function view($name)
{
$parts = explode('.', $name);
$template = '/views/' . implode('/', $parts) . '.php';
require_once __DIR__ . $template;
}
Then you can use it like so, storing all your view files in the ./views directory:
require_once './view.php';
view('home.message'); // {path}.{to}.{file} => /{path}/{to}/{file}.php
You can also write it as a class if you so wish.
PS - this code above was not tested, but the principle is sound and is aimed at creating a view file like this:
<!DOCTYPE html>
<html>
<head>
<?php view('layout.head'); ?>
</head>
<body>
<div class="wrap">
<?php view('layout.menu'); ?>
</div>
<!-- load conditionally -->
<?php if (isset($addFlag) && $addFlag == 1) view('add.message'); ?>
<?php view('layout.footer') ?>
</body>
</html>
I'd should simple enough to use the INCLUDE statement.

Where/How do I include the navigation bar in a yii view

I am new to PHP frameworks and yii and I am trying to understand how views/layouts work. This is how I currently understand how to layout a page template:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="page_wrp">
<?php include 'includes/top_right_nav.php' ?>
<div id="content_wrp">
<div id="content">
</div>
</div><!--#content_wrp-->
<?php include 'includes/main_nav.php' ?>
</div><!--#page_wrp-->
</body>
I understand that basic yii way is more like this:
<?php /* #var $this Controller */ ?>
<!DOCTYPE>
<html>
<head>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<div class="container" id="page">
<div id="header">
<div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div>
</div><!-- header -->
<div id="mainmenu">
<!--
DON'T WANT TO USE ZII.WIDGETS FOR MENU
WANT TO KNOW BEST WAY TO INCLUDE MY ONW NAVIAGTION MENU-
->
<?php $this->widget('zii.widgets.CMenu',array('...')); ?>
</div><!-- mainmenu -->
<?php echo $content; ?>
<div id="footer"></div><!-- footer -->
What I don't understand is what is the best practice/analogous way to include my own navigation bar in the context of yii/MVC. Can I still use includes as above or do I have to use zii.widgets? If it's ok to use includes where do I put the files?
Any help would be much appreciated.
You don't have to use Yii widgets however it's recommended to use them, they are quite flexible.
Make a view file for your menu markup in the layouts folder, something like _myMenu.php
_menu.php
<ul>
<li>menu item 1</li>
<li>menu item 2</li>
</ul>
then in your layout use renderPartial() to render your _menu.php partial view inside your layout.
main.php
<div id="mainmenu">
<?php $this->renderPartial("//layouts/_menu"); ?>
</div>
This is a really simple solution, if you want to make the menu more dynamic you can add a method to your controller to handle this.

swap stylesheet for jquerymobile with a link

I have a variable called $cat(which stands for 'category') in the URL.
Depending on whether it is "a" or "b" I swap the stylesheet using a link:
<?php
if($cat == "a") { ?>
<link rel="stylesheet" href="/css/styleA.css">
<?php }
elseif($cat == "b") { ?>
<link rel="stylesheet" href="/css/styleB.css">
<?php } ?>
styleA.css makes the background-color of the header blue, and styleB.css makes it red
<div id="header" data-role="header" data-position='fixed'>...</div>
if I click on a link that looks like this:
Click for red
Click for blue
the URL actually works (content is incuded depending on $cat) and I do get the value of $cat but the stylesheet does not seem to have swapped, since the color doesn't change. But if I reload the page (with the URL given by the link before) the stylesheets swap and everything works perfectly.
I used the same method for the desktop version of the website I'm working on and everything works perfectly fine.
This issue seems to only appear if I use jquery mobile.
Does anyone see why this isn't working as it should?
EDIT (adding html):
This is pretty much it, but here's the rest of it:
headpart:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title></title>
<link rel="stylesheet" href="https://d10ajoocuyu32n.cloudfront.net/mobile/1.3.1/jquery.mobile-1.3.1.min.css">
<!-- Extra Codiqa features -->
<link rel="stylesheet" href="/css/codiqa.ext.css">
<link rel="stylesheet" href="/css/style.css">
<?php if($cat == "a") { ?> <link rel="stylesheet" href="/css/styleASS.css"> <?php }
if($cat == "b") { ?> <link rel="stylesheet" href="/css/styleBB.css"> <?php }
?>
<!-- jQuery and jQuery Mobile -->
<script src="https://d10ajoocuyu32n.cloudfront.net/jquery-1.9.1.min.js"></script>
<script src="https://d10ajoocuyu32n.cloudfront.net/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<!-- Extra Codiqa features -->
<script src="https://d10ajoocuyu32n.cloudfront.net/codiqa.ext.js"></script>
</head>
<div data-role="page" id="page">
<div id="panel_menu" data-role="panel" data-display="overlay">
<ul data-role="listview">
<li role="heading">Navigation</li>
<li>Home</li>
<li>Products</li>
<li>Service</li>
<li>Contact</li>
<li>Login</li>
</ul>
</div>
<div id="header" data-role="header" data-position='fixed'>
<h1>Header</h1>
Menu
</div>
<div data-role="content">
<?php include "$menu_page_content";?>
a
b
</div>
<div data-role="footer" data-position="fixed" data-theme="d">
<div data-role="navbar" class="ui-icon-nodisc">
<ul>
<li><a href="#" id='language' data-icon='custom'>Change Language</a></li>
<li><a href="#" id='category' data-icon="custom" >Change Category</a></li>
<li><a href="#" id='contact' data-icon="custom" >Contact</a></li>
</ul>
</div>
</div>
</div><!-- page -->
EDITIT:
Uploaded it to a free hoster: here
You may either click on one of the links in the content area, or on "category" in the footer area. Click & reload the page.
If most of your styles are the same with the exception of the color I would suggest putting them in a single style sheet and writing in a class to the body.
For Example
.header {
/* general header styles margins paddings and whatnot */
}
.cat-a .header {
background-color: red;
}
.cat-b .header {
background-color: blue;
}
Then variably write the class in on the body
<body class='cat-<?php echo $cat; ?>'>
It must depends on how data are cached on the browser you're using.
Several solutions are possible.
You could not swap CSS stylesheet, but add style properties using PhP or Javascript. That way you'll be 100% sure it will change. (As long as the user has javascript by the way, PhP would make it really 100% sure)
Or force the browser to reload CSS sheets everytime, but it's not a bandwidth friendly solution, I would not recommend that.
In case you want to use it to save user's choice and reload the correct background everytime, give a look at this :
http://www.dynamicdrive.com/forums/archive/index.php/t-44389.html
Didn't find any SO link though

HTML Templates -- php?

So, I'm making a site about WWI as a school assignment, and I want this to appear in every document:
<!DOCTYPE html>
<html>
<head>
<title>1914</title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" type="text/css" rel="stylesheet" />
<meta charset="utf-8" />
</head>
<body>
<div id="container">
<header>
<img src="images/banner.png" alt="World War I" style="border: none"/>
<nav>
<ul>
<li><span>Home</span></li>
<li><span>1914</span></li>
<li><span>1915</span></li>
<li><span>1916</span></li>
<li><span>1917</span></li>
<li><span>1918</span></li>
</ul>
</nav>
</header>
<section>
<article>
<br style="clear: both" />
</article>
<aside>
</aside>
</section>
<footer style="font-weight: bold; letter-spacing: .1em">
Citations •
About
</footer>
</div>
</body>
</html>
I think it's kind of stupid to copy-paste all this into each document, and painstakingly go in and change each page separately if I just want to change one word or tag. Is there a way I can put this in template.htm (or something similar) and have php or javascript code take this and insert everything from the requested file inside of the <article> tag? I don't know a lot of php, so this is probably a piece of cake for you gurus, but I would appreciate the help.
Using php includes:
Save this as top.php
<html>
<head>
<title><?php echo $title; ?></title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" type="text/css" rel="stylesheet" />
<meta charset="utf-8" />
</head>
<body>
<div id="container">
<header>
<img src="images/banner.png" alt="World War I" style="border: none"/>
<nav>
<ul>
<li><span>Home</span></li>
<li><span>1914</span></li>
<li><span>1915</span></li>
<li><span>1916</span></li>
<li><span>1917</span></li>
<li><span>1918</span></li>
</ul>
</nav>
</header>
<section>
Save this as bottom.php
<aside>
</aside>
</section>
<footer style="font-weight: bold; letter-spacing: .1em">
Citations •
About
</footer>
</div>
</body>
</html>
Then your individual pages would be like this:
<?php $title = '1914'; include("top.php");?>
//This would be where you would make the changes that need to be made on each page.
<article>
<br style="clear: both" />
</article>
<?php include("bottom.php");?>
You could consider one of these popular template engines :
Smarty (becoming outdated)
Latte (used mostly by the Nette community)
Twig (used mostly by the Symfony community)
Mustache (official implementations of this templating engine exist in more than two dozen proramming/scripting languages)
I tend to favor Mustache, mostly because it has an official JS version, an official Ruby version, an official Java version, etc. It allows you to use the same templates frontend and backend, which is very useful for widgets that are first rendered in background and rerendered in foreground at updates.
Put the content in a file abc.php
and then add this to each page you want the desired content in :
<?php
include("abc.php");
?>
So if your code is :
<nav>
<ul>
<li><span>Home</span></li>
<li><span>1914</span></li>
<li><span>1915</span></li>
<li><span>1916</span></li>
<li><span>1917</span></li>
<li><span>1918</span></li>
</ul>
</nav>
</header>
<section>
<article>
<br style="clear: both" />
</article>
<aside>
</aside>
</section>
And you want the part inside <nav> to be repeated in each page, you can put the content between <nav> and </nav> (including the tags) inside abc.php and include abc.php in your file like this :
<?php
include("abc.php");
?>
</header>
<section>
<article>
<br style="clear: both" />
</article>
<aside>
</aside>
</section>
Create the template file as a single file, exactly you have it already, but printing PHP variables in the places where you want content.
eg:
....
<article>
<?php print $mainContent; ?>
</article>
....
Then write a PHP function as follows:
<?php
function insertContentIntoTemplate($mainContent) {
require_once('/path/to/template.php');
}
?>
Now you can load your page content into the template simply by calling the function and passing the content into it for each page.
So, for example, 1914.php could look like this:
<?php
require_once('/path/to/insertFunction.php');
//the text could be loaded from a DB, or from another file, or just as a plain string like this:
$text = "The year was 1914, and the war was just starting.";
insertContentIntoTemplate($text);
?>
Congratulations. You now have a working (albeit very simple) template system. Add more variables / placeholders to your template as required.

How could I improve this template system?

At the moment, I have a base HTML template file. When ever I want to make a new page, I copy the template and place some require_once statements in between specific tags. I was wondering if there's a better way that would make it unnecessary to copy the template each time. Here's a typical example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title>Order a Ticket for the ball</title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text">introduction</div>
<div id="header_cell2">the process</div>
<div id="header_cell3">start</div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($config["directories"]["views"]."/index.form.view.php"));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($config["directories"]["views"]."/index.data.view.php"));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($config["directories"]["views"]."/index.side.view.php"));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
EDIT: I have taken note of your suggestions to use GET. The new idea is to have each request url formed as index.php?page=page_name. This request would then be dealt with by a main controller which then sets the variables of the template based on the value of $_GET['page']. For this, the template will now be:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title><?php h($title) ?></title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text"><?php h($header_1) ?></div>
<div id="header_cell2"><?php h($header_2) ?></div>
<div id="header_cell3"><?php h($header_3) ?></div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($view_1));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($view_2));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($view_3));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
Note: h() is a function that first of all removes all undesired entity tags before echoing a string.
On a related note, at the top of each page I have some controller files which are included with require_once. I was wondering if it would be possible to implement a function that simply includes files based on a specific input string (name of the functionality/page) i.e "index" in this way:
function include_controller($page){
switch($page){
case "index":
require_once(realpath($config["directories"]["controllers"]."/index_.php"));
break;
case "checkout":
require_once(realpath($config["directories"]["controllers"]."/checkout_.php"));
break;
default:
break;
}
}
Instead of hard coding the includes into each file, you could have a controller file in which you pass the page to be displayed through a $_GET variable. The controller then handles the logic and includes the appropriate page or pages. This is the way a lot of MVC frameworks do it.
Edit: To answer your second question, instead of using a switch, you could just check to make sure the file exists. If it does, include that file, otherwise output an error ("Page doesn't exists" or something similar).
function include_controller($page){
if (file_exists($config["directories"]["controllers"]."/$page_.php")) {
// page exists, include it
require_once($config["directories"]["controllers"]."/$page_.php"));
} else {
// page not found
}
}
Obviously you should probably make the function a little more robust and probably limit the files that will be included to a certain directory or something. Also make sure you properly filter the $page variable so users aren't able to access any file.
Keep this one file as your template file. Then for all the functionality in your site always hit this file. Lets sat this file is index.php. So all functionality requests go to index.php. But with different parameters so for functionality A.
index.php?function=a
For functionality b
index.php?function=b
you can add more parameters also.
Now on the basis of a,b and the set of parameters see what files you want to include as require once.
Like the others already said, it would be better to use some kind of MVC framework. Or at least use a template engine (e.g. Smarty). Your example is ok though, for the 90ies :)
You can get by with one template if you choose a different way of specifying what page is being requested, such as using a GET variable. You can load the pages in a database and specify each of the included pieces, then have one php 'template engine' that loads the requested page from the database and outputs the template with the right includes.
If your server supports it, you can references to things you want to include on all pages in .htaccess:
php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"
(Found this on codingforums.com)

Categories