Multiple <head> and <body> tag - php

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.

Related

I need to replace some portion of my code automatically, among all files in a directory

I'm trying to convert a large website into PHP. All the files have almost similar head/header portion and footer section.
I'm trying to unify all these header section, and footer section by putting it into a seperate file.
So I need to replace all of my
header section (which spans anywhere from 1045 to 1535 lines) with
<?php include_once "include/header.php" ?>
And
footer section (which spans anywhere from 80 to 140 lines) with
<?php include_once "include/footer.php" ?>
from all the files in a directory..
This is a rough figure of what I need to do.. Please look the code below..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="">
<meta name="description" content="">
<meta name="author" content="">
<title></title>
<link rel="apple-touch-icon" href="">
<link rel="shortcut icon" href="">
<!-- Stylesheets -->
<link rel="stylesheet" href=""> <!-- Some Stylesheets -->
<link rel="stylesheet" href=""> <!-- Some Stylesheets -->
<link rel="stylesheet" href=""> <!-- Some Stylesheets -->
<!-- Scripts -->
<script src=""></script>
</head>
<body class="">
<nav class="nav1" role="navigation">
<!-- Some HTML -->
</nav>
<div class="menubar1">
<!-- Some HTML -->
</div>
<div class="menubar2">
<!-- Some HTML -->
</div>
<!-- ========================================================= -->
<!-- ========================================================= -->
<!-- PAGE CONTENTS -->
<!-- ========================================================= -->
<!-- ========================================================= -->
<!-- Footer -->
<footer class="site-footer">
<!-- Some HTML -->
</footer>
<script src=""></script> <!-- Some Script Tags -->
<script src=""></script> <!-- Some Script Tags -->
<script src=""></script> <!-- Some Script Tags -->
<script src=""></script> <!-- Some Script Tags -->
<!-- Page -->
<!-- Google Analytics -->
<script>
/* Some Scripts */
</script>
</body>
</html>
In the above given code, I need to replace everything from top to
<div class="menubar2">
(Until it's closing Tag)
with
<?php include_once "include/header.php" ?>
Also, I need to replace everything below footer
with
<?php include_once "include/footer.php" ?>
Please help me replace that portion of the file with my string..
Thanks in advance🙂..
First, note that regular expressions should generally never be used with DOM. However, since we're talking mass replacing within files, I suppose this is acceptable in this case (you don't want to lose the formatting, and mass deleting nodes with DOM would be awkward as well).
Now, taking into account what you said in the other comment about the structure of your menubar2 div, this should do it.
Edit: now with dynamic number of divs under menubar2:
// Compute the amount of divs within `menubar2` div
libxml_use_internal_errors(true);
$doc = new \DOMDocument();
$doc->loadHTML($html);
$menubar2_inner_div_count = (new \DOMXPath($doc))
->query('//div[#class="menubar2"]//div')
->length;
// Header
$html = preg_replace(
'/^.*?<div class="menubar2">' . str_repeat('.*?<\/div>', $menubar2_inner_div_count + 1) . '/s',
'<!-- Header -->' . PHP_EOL . '<?php include_once "include/header.php" ?>',
$html
);
// Footer
$html = preg_replace(
'/<footer class="site-footer">.*?<\/html>/s',
'<?php include_once "include/footer.php" ?>',
$html
);
// (Optional) Remove now useless indentation (supposes your indent is 8 spaces,
// otherwise replace accordingly)
$html = preg_replace('/^ {8}/m', '', $html);
Demo: https://3v4l.org/G3HbK
This is a quick rough fix... didn't test it but hope it works!
Quick heads up! If you are planning on adding <div> inside <div class="menubar2"></div> then add this <div class="match-hidden"></div> after </div> closing tag of class .menubar2.
Change first preg_match with preg_match('/<!DOCTYPE html>(.*?)<div class="match-hidden">(.*?)<\/div>/s',$file,$newfile);
$file = file_get_contents('replace_head.html');
preg_match('/<!DOCTYPE html>(.*?)<div class="menubar2">(.*?)<\/div>/s',$file,$newfile);
preg_match('/<footer class="site-footer">(.*?)<\/html>(.*?)/s',$file,$newfile2);
if($newfile == TRUE){
$file1 = str_replace([$newfile[0]],['<?php include_once "include/header.php" ?>'],$file);
if($newfile2 == TRUE){
$file2 = str_replace([$newfile2[0]],['<?php include_once "include/footer.php" ?>'],$file1);
//header('content-type:plain/text');
//Un-comment this if you want to download current file
header('content-type:application/json');
//Comment this if you want to see it as html
echo($file2);
}
}

PHP: Is it possible to modify varibles of an included php file?

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 = '';
}

How do I make header and sidebar stay?

This is my index.php file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
</style>
</head>
<body>
<div id="container">
<?php
include('includes/header.php');
include('includes/sidebar.php');
include('includes/content.php');
include('includes/footer.php');
?>
</body>
</html>
This is code for my sidebar.php
<div id="sidebar">
<ul id="list">
<li>Home</li>
<li>flower</li>
<li>Study</li>
<li>Calendar</li>
<li>Diary</li>
</ul>
if I click flower, it will go to flower.php. I didn't include header, sidebar, and footer, and found that it shows only contents of flower.php, not showing header, sidebar, and footer. Is there any way to make it showing? Or should I just write down all the code below again?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
</style>
</head>
<body>
<div id="container">
<?php
include('includes/header.php');
include('includes/sidebar.php');
include('includes/content.php');
include('includes/footer.php');
You should use your header, footer and sidebar on each of your page, because it won't create any problem because if you need to make change you would only change in required file and the change will occur in all other files as well. While content.php you should have your specific code for each page separately.
Hope this help

How to add css files using PHP inside the <head> tag?

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" />

How to add content to PHP include files?

Ok I may not have the best title , but I will try to give a better explanation.
Let's assume you are using PHP include() to structure your website:
Header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name=keywords content="somthiefn"/>
<title>Website</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
<script src="Scripts/jquery-1.8.3.min.js"></script>
<link rel="icon" type="image/png" href="/images/favicon.ico" />
</head>
<body>
Footer.php
</body>
</html>
Then a sample page:
Index.php
<!--Header-->
<?php include ('includes/header.php'); ?>
<div class="content">
<!-- some content-->
</div>
<!--Footer-->
<?php include ('includes/footer.php'); ?>
Basically I just want to know if there is a way to load some script into my header section.
I would like to achieve something like ASP.NET and its master Page, where I can just add content the header. for example
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script src="Scripts/somescript.js"></script>
</asp:Content>
Yes, you can do like this:
index.php
<?php
// Wanted page title
$title = "some";
// JS Files..
$scripts = array();
$scripts[] = '<script src="js/some.js" />';
$scripts[] = '<script src="js/some2.js" />';
$scripts[] = '<script src="js/some3.js" />';
// Include header
include ('includes/header.php');
header.php
<title><?php echo $title ?></title>
<?php echo implode("\n",$scripts) ?>
Of course the variables could be named as you want and contain any data. Main thing is that you can pass them between files like i showed.
In index.php, before you include header.php, you could set an array for your scripts like:
header.php
<?php if(!isset($scripts)) $scripts = array(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name=keywords content="somthiefn"/>
<title>Website</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
<script src="Scripts/jquery-1.8.3.min.js"></script>
<link rel="icon" type="image/png" href="/images/favicon.ico" />
<!-- Include dynamic scripts-->
<?php foreach($scripts in $script): ?>
<script src="<?php echo $script; ?>"></script>
<?php endforeach;?>
</head>
<body>
index.php
<?php
$scripts = array('Scripts/somescript.js', 'http://server.com/path/anoterscript.js);
?>
<!--Header-->
<?php include ('includes/header.php'); ?>
<div class="content">
<!-- some content-->
</div>
<!--Footer-->
<?php include ('includes/footer.php'); ?>
Do you want to add PHP code to the header? Then you can add your code between tags (or tags if short tags are enabled), but I would consider to just call an include between the PHP tags and have the logic in that include.
Another option could be a template engine, e. g. Smarty. In most of the templates engine you can define your own functions and call them from the templates.
You could do this:
// content.php
<?php
$head = "<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='keywords' content='somthiefn' />
<title>Website</title>
<link type='text/css' rel='stylesheet' href='css/style.css' />
<script src='Scripts/jquery-1.8.3.min.js'></script>
<link type='image/png' rel='icon' href='images/favicon.ico' />
</head>
<body>";
$foot = "\n<body>\n</html>";
?>
// index.php
<?php
include 'includes/content.php';
$dom = new DOMDocument; #$dom->loadHTML($head);
$hd = $dom->getElementsByTagName('head'); $hd = $hd->item(0);
$script = $dom->creatElement('script');
$scriptAttr = $dom->createAttribute('src');
$scriptAttr->value= 'Scripts/somescript.js'; $script->appendChild($scriptAttr);
$hd->appendChild($script);
echo $dom->saveHTML().$foot;
?>
The other option is to use variables to separate your code then only echo portions. That is what I would do. It's technologically faster. Try this:
// content.php
<?php
$headTop = "<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='keywords' content='somthiefn' />
<title>Website</title>
<link type='text/css' rel='stylesheet' href='css/style.css' />
<script src='Scripts/jquery-1.8.3.min.js'></script>\n ";
$headBottom = "\n <link type='image/png' rel='icon' href='images/favicon.ico' />
</head>
<body>";
$foot = "\n<body>\n</html>";
?>
// index.php
<?php
include 'includes/content.php';
echo "$headTop<script src='Scripts/somescript.js'></script>$headBottom$foot";
?>
You can see why you would use the second option.
This works for me. It dynamically loads title, scripts and styles.
header.php
<?php
if(!isset($scripts))
$scripts = array();
if(!isset($styles))
$styles = array();
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title ?></title>
<link rel="stylesheet" href="css/somestyle.css" type="text/css">
<script src=somescript.js"></script>
<!-- include styles -->
<?php foreach($styles as $style): ?>
<link href="<?php echo $style; ?>" rel="stylesheet">
<?php endforeach; ?>
<!-- include scripts-->
<?php foreach($scripts as $script): ?>
<script src="<?php echo $script; ?>"></script>
<?php endforeach;?>
</head>
<body>
index.php
<?php
$title = "some dynamic title";
$scripts = array('js/somescript.js', 'http://server.com/anoterscript.js');
$styles = array('css/somestyle.css', 'css/anotherstyle.css');
require_once ('header.php');
?>
<div class="content">
<!-- some content-->
</div>
<?php require_once('footer.php'); ?>

Categories