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.
Related
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 } ?>
...
I am new to php.
I have a header.php with variables which I want to be uniquely set depending on which php page includes the header.php. I want each page that loads the header to display unique data in the header - current page info.
Currently I have something like the following:
header.php
<?php $pageInfo = "";?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/header.css">
<title></title>
</head>
<body>
<div id="header-box">
<div id="header-wrapper">
<div id="logo-box">
</div>
<div id="info-box">
<div>
<p><?php echo $pageInfo ?></p>
</div>
</div>
</div>
</body>
</html>
page1.php
<body>
<div><?php $pageInfo = ":D"; require 'shared/header.php'; ?></div>
<div><?php include 'shared/menu.php';?></div>
</body>
Yes that is possible. Include works like as you have have merged multiple pages (Scripts) into one. So if you want to change the value of variables in header.php before including header.php define them.
ex:
<?php
$pageInfo = 'Test page';
require_once 'header.php';
?>
Note: Do not declare $pageInfo = '' in header.php else it will over write it. You can do as follow in header.php:
if(!isset($pageInfo)) {
$pageInfo = '';
}
regarding working control flow if the page has 2 html tags
<html>
.....
</html>
<html>
.....
</html>
WHICH WOULD BE EXECUTED BOTH OR THE ONLY FIRST ONE....
I am working on a cs50 project in which when i call
<?php
dump($_SERVER);
render("login_form.php", ["title" => "Log In"]);
?>
only dumps get executed whereas when
<?php
render("login_form.php", ["title" => "Log In"]);
dump($_SERVER);
?>
both gets executed
the details of dump and render function are..
function render($template, $values = [])
{
// if template exists, render it
if (file_exists("../templates/$template"))
{
// extract variables into local scope
extract($values);
// render header
require("../templates/header.php");
// render template
require("../templates/$template");
// render footer
require("../templates/footer.php");
}
// else err
else
{
trigger_error("Invalid template: $template", E_USER_ERROR);
}
}
function dump
function dump($variable)
{
require("../templates/dump.php");
exit;
}
the templates file are
dump.php
<!DOCTYPE html>
<html>
<head>
<title>dump</title>
</head>
similar are header.php
<!DOCTYPE html>
<head>
<link href="/css/bootstrap.min.css" rel="stylesheet"/>
<link href="/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="/css/styles.css" rel="stylesheet"/>
<?php if (isset($title)): ?>
<title>Mobi3: <?= htmlspecialchars($title) ?></title>
<?php else: ?>
<title>Mobi3</title>
<?php endif ?>
<script src="/js/jquery-1.10.2.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/scripts.js"></script>
</head>
<body>
<div class="container">
<div id="top">
<img alt="C$50 Finance" src="/img/logo.gif"/>
</div>
<div id="middle">
<body>
<pre><?php print_r($variable); ?></pre>
</body>
footer.php
<div id="bottom">
Copyright © M3shop
</div>
</div>
</body>
If the answer is "having two sets of html tags" you are asking the wrong question. Regardless on which one is shown (which can also vary from browser to browser).
I am trying to create a very simple web application, basically to understand the best practices of coding in HTML5, CSS and JavaScript.
My application has 3-4 pages and each one is using same menu header. So I want to make it reusable by writing it in a separate file (either PHP or HTML).
head.php (it is to be made reusable):
<!DOCTYPE html>
<html>
<head>
<link href="../../css/headermenu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ul id="menu">
<li>Home<span></span></li>
</ul>
<p>
</p>
</body>
</html>
front.php:
<?php
include ("$_SERVER[DOCUMENT_ROOT]/page/common/head.php");
?>
HTML markup (dirty code):
<!DOCTYPE html>
<html>
<head>
<!DOCTYPE html>
<html>
<head>
<link href="../../css/headermenu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ul id="menu">
<li>Home<span></span></li>
</ul>
<p>
</p>
</body>
</html></head>
<body>
<div>
</div>
<p>
</p>
</body>
</html>
I have following questions:
head.php has both <body> and <head> tag. So where should I write these PHP lines to include it? (in <head> or <body>) (I don't want to have multiple <head>s and <body>s in the final page)
What are the other best practice I should follow? (any link to references welcome)
I have already read w3schools.
In my opinion it would be a good idea to read about templating systems or have a look how frameworks/CMS handle this.
Doing it your way, you can't completly avoid repeating e.g. the closing head tag </head> in every content.php.
So this is just an idea:
head.php
<?php
// Some other includes / requires,
// code snippets...
?>
<!DOCTYPE html>
<html>
<head>
<!-- site-wide stylesheets -->
<!-- & js-files -->
<link href="css/main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="my/global/scripts.js"></script>
content.php
<?php
include ($_SERVER['DOCUMENT_ROOT'] . '/page/common/head.php');
?>
<!-- put page specific scripts &
<!-- styles here -->
<link href="my/pages/css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="my/pages/js/scripts.js"></script>
</head>
<body>
<div id="container">
<!-- content start -->
<div id="content">
<h1>title</h1>
<p>Your content</p>
</div>
<!-- end of content div -->
<?php
include ($_SERVER['DOCUMENT_ROOT'] . '/page/common/foot.php');
foot.php
<div id="foot">
copyright etc
</div>
</div> <!-- end of container div -->
</body>
</html>
php is rendering html and if you have in both files header of course it will be printed twice
you should separate in includes but don't write in both files tag
example
<header>
<?php
// this file should not include <head> taf
include ($_SERVER[DOCUMENT_ROOT] . '/page/common/header.php);
?>
</header>
BODY
<header>
<?php
include ($_SERVER[DOCUMENT_ROOT] . '/page/common/foot.php);
?>
</header>
include will bring content from head.php and foot.php and will put in index.php file
Another possible solution to avoid multiple head tags which also makes it possible to add additional css files:
<?php
// head.php
$html = <<< EOF
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<title>{$title}</title>
{$meta}
<link href="../../css/headermenu.css" rel="stylesheet" type="text/css"/>
{$additional_style}
</head>
<body>
<ul id="menu">
<li>Home<span></span></li>
</ul>
{$mainbody}
{$footer}
{$javascript}
</body>
</html>
EOF;
?>
<?php
// page1.php
$title = 'some title';
$meta = '';
$additional_style = '';
$mainbody = 'your body';
$footer = '';
$javascript = '';
include_once("head.php");
echo $html;
?>
<?php
// page2.php
$title = 'some other title';
$meta = '';
$additional_style = '<link href="../../css/page2.css" rel="stylesheet" type="text/css"/>';
$mainbody = 'your body';
$footer = '';
$javascript = '';
include_once("head.php");
echo $html;
?>
It also allows for multiple levels of inheritance (for example, you could define the same footer for a couple of pages). This principle can also be used without EOF, but I think that it looks nicer this way.
The main downside is that you will get a warning if you do not set all the variables of head.php in the pages including it.
Ok, let me explain:
I have a some files, something basic like this:
index.php
<html>
<head>
<title>Simple page</title>
</head>
<body>
<?php include 'home.php'; ?>
</body>
</html>
home.php
<div class="thisWillBeBlue">Still not blue</div>
style.css
.thisWillBeBlue {background: blue}
Now the question: Using php I want to insert the style.css inside the head tag, calling it from the file home.php. Well, I came out with a solution, but it was not very effective:
index.php
<?php $css = array();
$css[] = 'linktothecss.css'
?>
<html>
<head>
<title>Simple page</title>
<?php
foreach($css as $item){
echo "<link rel='stylesheet' href='".$item."' />";
}
?>
</head>
<body>
<?php include 'home.php'; ?>
</body>
</html>
But the problem it is, If I call the css from home.php it will be added to the array later, therefore it will not be echoed inside the head tag. Any ideas?
You could do it using ob_start() and ob_end_flush() functions
e.g.
index.php
<?php
$csspage = "default.css";
function loadCSS($buffer) {
global $csspage;
return (str_replace('{{ css }}', $csspage, $buffer));
}
ob_start("loadCSS"); ?>
<html>
<head>
<!-- the string {{ css }} is just a placeholder that will be replaced
with the new value of $csspage defined later in the code, otherwise
it will replaced with its initial value (default.css)
-->
<link href="{{ css }}" />
</head>
<body>
<?php include 'home.php'; ?>
</body>
</html>
<?php ob_end_flush(); ?>
home.php
<?php $csspage = "custom_style.css"; ?>
<div class="thisWillBeBlue">blue</div>
Further reference: http://it1.php.net/ob_start
I think you are looking for something like this ..(include a piece of code in their header files, so that it will allow you to add more stylesheets )
This will allow you to add more stylesheets to it on each page.
(add this to <head>)
<?php
if (!empty($styles) && is_array($styles)) {
foreach ($styles AS $style) {
echo '<link rel="stylesheet" href="/assets/css/'. $style .'">';
}
}
?>
You can put a variable at the top of an individual script if you need a specific stylesheet:
<?php
$styles = array('custom_style.css');
?>
CSS file references can be placed in the body of your code, if needed.
<body>
<link href="linktothecss.css" rel="stylesheet" type="text/css" />
<div class="thisWillBeBlue">
I'll be blue as soon as linktothecss.css finishes loading!
</div>
</body>
The only difference is that when in the HEAD, they are guaranteed to be loaded before the page is rendered. When they are in the BODY, there may be a split-second where they are still loading and the styles haven't been applied yet.
If you definitely want them in the HEAD, you could define the css requirements in a separate folder with the same file name, like so:
index.php:
<html>
<head>
<?php
include('css-requirements/home.php');
?>
</head>
<body>
<?php include('home.php'); ?>
</body>
</html>
and
css-requirements/home.php:
<link href="mycss.css" rel="stylesheet" type="text/css" />
<link href="myothercss.css" rel="stylesheet" type="text/css" />