Minimize code size to avoid duplication of the same code - php

I need one advice from you. I am working on a website, which uses PHP and HTML. As the biggest part of the header and footer code will be same for many pages, I am thinking of using PHP's include to avoid code duplication. But, each of those pages requires different stylesheets and JS files included. What do you think how could I let the other file know what scripts and stylesheet to import?

Our company does this:
The header reads the filename of the page calling it when it's included.
Then, it changes the extension to '.js' and outputs that if it exists. Same for CSS.
So if I have a page "register.php", it will auto-include "register.js" and "register.css" if they exist.

Here's what I do:
<?php include("includes/headContent.php"); ?>
<title>Page title goes here!</title>
<script src="script_only_used_on_this_page"></script>
<?php
require_once("includes/siteHeader.php");
?>
Site Content Goes Here!!
<?php
require_once("includes/siteFooter.php");
?>
Head Content includes any PHP I want included in every page, as well as the opening html and head tag, and any Javascript libraries and css stylesheets I want on every page. Site header closes the /head tag, and opens the body as well as printing out my site header and some other markup that goes on every page. Finally Site Footer closes out my template. Everything in between is my content area!

There are lots of different ways you can do templating, if you wanted to create a simple include and an echoHeader() and an echoFooter() function... just have the echoHeader function accept a parameter which you would pass your javascript and CSS lines to.

you can use MVC coding pattern

Related

How to change many webpages in a website?

I am making website and this website will have more than 20pages.
I am using my template to add a webpage. This template has header and footer, so I just add the body of new page.
But, what if I want to change navigation bar in the header, then I have to change all 20 pages that I already made to correct.
I want to know better way.
I read a book, and it says about "php include" function.
Should I use this function in the header and footer of each webpage to call header and footer file?
If I want to change the navigation bar in the header, all I can do is changing only one header file, then rest of website will be changed.
Is this correct way?
In this case, what do you do?
I am a beginner, so please advise me.
Thank you in advance.
You should build your website as following. The header.html would contain the navigation.
header.html
<!doctype html>
<html>
<head>
...
</head>
<body>
<nav>
...
</nav>
footer.html
<footer>
...
</footer>
</body>
</html>
page.php
<?php
require_once 'header.html';
?>
Your content goes here
<?php
require_once 'footer.html';
?>
You should use require_once so the header and footer will be imported only once per script and if the header or footer cant be found, the script will throw an exception and stop the "application".
"require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!
Yes this is the correct way or you could just copy your header and footer code to every .html file (if you don't like PHP)
Yes, this is the correct way. Try to think of the DRY principle - don't repeat yourself. Elements of your web page that are common across multiple pages can be coded once, then called in. If you need to update these elements, you update them once and it affects all pages.
You then "include" these elements into your page, and the elements are self contained files. As a basic example you would have header.php
<html>
<head><!-- all of your head meta tags in here--></head>
<body>
<div id="header"><!--your header elements and top menu in here --></div>
and footer.php:
<div id="footer"><!-- your footer elements in here--></div>
</body>
</html>
Don't forget in both header and footer files you can then put dynamic code if you wish. Then for each of your pages you would simply call these files in using include, include_once, require or require_once
<?php
include('header.php');
//this is where your actual page content goes
include('footer.php');
?>
A very basic example, but hopefully that makes sense to you.
Correct.
If you include another php file it will calculate/ask for input/do output (whatever you do in the file) as part of your main file.
If you include a php file that has a function you can later call this function without it showing in your main file. (Saves space in your main file)
So your 20 pages may only need a few lines of body text and the rest is header and footer. This will make changes very easy

PHP - Add 'meta' tag to all pages loading the script, and this script is outside 'head' tag

I need to add a meta tag to all files of a website, so I thought about adding that meta tag by PHP code, within header.php, menu.php or footer.php; something like:
<?php addToHeadTag("Meta: favicon='./img/favicon.ico'"); ?>
It has a lot of files and manually changing each file is out of hand.
P.S.: All possible files in which I could include that code are outside head.
First of all, you can place an include file wherever you like in your code. Though that really has nothing to do with the problem at hand.
You should not be using header() for this. header() provides the client browser with meta information on the http response as a whole.
Take a look at this link for usage information on favicons:
http://en.wikipedia.org/wiki/Favicon
In most cases you can just place the favicon.ico in your web root and the browser will pick it up automatically without any markup at all. You can also use a <link> element.

PHP includes header or footer location

I was hoping someone could help. I have just started to dabble with PHP includes for time saving in the future. For example I want to change the footer and header on a web page once (using include) instead of copying and pasting the code 30 or 40 times - oh no... a typo start again.
Which brings me to the question(s) where is it best to place this script?
<?php include("includes/headernav.html"); ?>
Can it be placed in a div, or should it be placed at the top of your code under the body?
If I want to make an image/banner include module. Can I
<?php include("includes/image.jpg"); ?>
Or is best to wrap the image in html and apply like this?
<?php include("includes/imagewrapped.html"); ?>
Do not include .jpeg files directly, use a wrapper. Only use include with other PHP files.
As for including the header, do it any way that feels natural as long as it produces valid html. There is no particular reason to declare another div element.
Hope this helps:
<?php include("includes/ui_header.php"); ?>
My page content between header and footer
<?php include("includes/ui_footer.php"); ?>
You can probably save this as a function and call that function wherever you want to display.
It doesn't matter whether you put include in any place. However, it's better to put include in the top or bottom of your code
While including headers/footers/menus on the site, please keep in mind following things:
1) Your header/footer includes(blocks) should be wrapped inside a div.
2) This way then can be differentiated and any new change to them can be done easily.
3) Its always a good practice to include a wrapper div around an element as CSS can use it for styling.
4) Your header/footer includes (blocks) should have a flexibility that even we place them in header,footer or any sidebar, they should not disturb the UI.
1) Because you are including the HTML file, you probably need to include it where you want to display it.
2) Create a function in php where you send only image URL (maybe some other parameters) and function returns the HTML code (String) which you only echo on page where you want to display it. This way you can ensure, that all images will have the same code and styling.
for example
function generateImage($url=null) {
if (isset($url)) return '<img src='.$url.' style="width: 100px; height:100px; border: 1px;" />';
else return false;
}
The better way is to include always a php file.

Simulate PHP Include Without PHP

I want to include the same navigation menu on multiple pages, however I do not have PHP support, nor can I affect my server in any other way.
I want to avoid simply copying and pasting the html onto all the pages as this would make updating the menu a pain.
The two options I can think of are as follows:
1) Have all the content exist on one page, then determine which content to show based on a keyword appended to the url:
example.com/index?home
example.com/index?news
2) Include a javascript file that has a function that writes the menu out and call the function on each page
function setupMenu() {
$("#nav").html("<ul class='nav'><li>home</li><li>news</li></ul>");
}
With Option 1, the updating process would consist of editing one nav menu on the one page
With Option 2, updating would mean changing the function in the javascript file
My concern with Option 1 is that the page would have to load a lot of content that it wouldn't need to display. My concern for Option 2 may seem trivial but it is that the code can get messy.
Are there any reasons doing it one way would be better than the other? Or is there a third superior option that I'm missing?
You have a few options, each with its own advantages and drawbacks:
Server Side Includes, or SSI. If you don't have PHP there's a good chance you don't have SSI either, and this option requires some irritating mucking-about with your .htaccess file. Check Dominic P.'s answer for a writeup of SSI. The benefit of SSI over JavaScript or Frames is that it doesn't require the user to have JS enabled - which a lot of users don't - and it also doesn't present any navigational difficulties.
Frames. You could either use standard frames to put the navigation in its own separate file, and with the correct styling it would be seamless. You could also use an iframe to place your navigation in an arbitrary part of the site, like a sidebar or whatever. The downside to frames, particularly standard frames, is that they tend to make bookmarking, links and the forward/back buttons behave oddly. On the upside, frames don't need browser compliance or server support.
JavaScript. You can refer to any of the other answers for excellent explanations of the JS solution, particularly if you're using jQuery. However, if your site isn't otherwise dynamic enough that your users will want to have JavaScript enabled, this will mean that a large number of your viewers will not see the menu at all - bad, definitely.
-
Yes use .load jQuery ajax function
$('#result').load('ajax/menu.html');
That way your code stays clean, and you can just edit the includes in seperate HTML files just like PHP.
You should consider AJAX for this task. Include a third party library like jQuery and load the separate HTML files inside placeholders, targeting them by ID.
E.g, in your main HTML page:
<div id="mymenu"></div>
Also, in your main HTML, but in the HEAD section:
$('#mymenu').load('navigation.html');
But your best bet would be to switch to a hosting that supports PHP or any other server-side includes. This will make your life a lot easier.
Check out Server Side Includes. I don't have a whole lot of experience with them, but from what I recall, they are designed to be a solution to just your problem.
Server-side includes: http://www.freewebmasterhelp.com/tutorials/ssi/
You can use HTML Imports http://w3c.github.io/webcomponents/spec/imports/
Here is an example from http://www.html5rocks.com/en/tutorials/webcomponents/imports/
warnings.html contains
<div class="warning">
<style scoped>
h3 {
color: red;
}
</style>
<h3>Warning!</h3>
<p>This page is under construction</p>
</div>
<div class="outdated">
<h3>Heads up!</h3>
<p>This content may be out of date</p>
</div>
Then index.html could contain
<head>
<link rel="import" href="warnings.html">
</head>
<body>
...
<script>
var link = document.querySelector('link[rel="import"]');
var content = link.import;
// Grab DOM from warning.html's document.
var el = content.querySelector('.warning');
document.body.appendChild(el.cloneNode(true));
</script>
</body>

Preventing jQuery from Loading

If jquery is added in globally used header.php across the site then How to stop to load jquery library only for those pages of site which doesn't need actually? If we can't use more than one header.
purpose of question is to not to penalize those page with slow loading which actually don't need.
Your site shouldn't need more than one global-header, if you opt to even use headers to begin with. If it does, just include jQuery on all pages. It's a small cached file, it won't hurt the browsing experience.
By using the google-hosted version, it may be the case that many of your uses already have it cached before they even reach your site.
I have been guilty of pounding my fist into the nail while asking everyone else to move the hammer that's in the way...
Why not tackle the problem from the other end and use jQuery to optimize the first load?
If you have big pages that are already taking a while to download, why not section off the less-performant areas and use $().load() to fill those in?
The page will load quicker (better user experience) and you don't have to be adding any additional processing to pages that don't need it.
Cheers,
-jc
assuming you are loading the jQuery file from a correctly-configured webserver (or from google's CDN), it will be cached and not re-downloaded on each page. Assuming a visitor will hit at least one page on your site that needs jQuery then you really won't gain anything by trying to remove it from loading on pages that don't use any javascript features from the library.
First, use the compressed jquery for production. It's much smaller. Second, IIRC, once jquery is downloaded with the first page, it will be cached and won't need to be retrieved from your server for each subsequent request.
Otherwise, if you really need to explicitly load jquery only on those pages that need it, you would have to have some way for the body of your page to tell header.php that it doesn't need to load jquery. If header.php is loaded before "body.php" then that's pretty hard to do without some fancy output buffering or such.
If you're using a templating system like Smarty you could have a conditional in the master page template to check a $loadjquery flag that you set in body.php before sending the whole page off to be rendered. But that's complicated too.
Your question is very general, some specific would be great, maybe even a link to the site. Personally if you are using a CMS I would try to make some sort of "flag" for that page, or if you are simply loading a page and then loading the header from that page, insert a variable before you load the header and use that as your flag for loading jQuery.
An example:
If a user wants to see www.mysite.com then the following file would be loaded: www.mysite.com/index.php with the following code:
<?php $needJQuery = true;
include('header.php');
echo 'content will go here';
include('footer.php'); ?>
header.php would include something such as this:
<?php if ($needJQuery) { ?>
<script src="/jquery/jquery-min-3.2.1.js" />
etc. for all the content that you need above/below.
<?php } ?>
For the pages that don't need jQuery loaded, you would either leave $needJQuery undefined or you would do as follows:
<?php $needJQuery = false; ?>
Hope this helps,
As stated earlier, modify the header file so it'll check for the presence of flag variable and only output the jquery headers if needed.
If you don't have the ability to modify the header file, you could load it with output buffering turned on and filter the output before it heads out to the client:
<?php
ob_start();
include('header.php');
$header = ob_get_flush();
$cleanheader = some_operation_that_removes_the_jquery_script_tags($header);
echo $cleanheader
?>

Categories