Load page styles after php inserts html - php

I have my index.php call to insert a html section during the page load:
index.php:
<html>
<head>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<!-- navigation -->
<?php include 'navigation.html'; ?>
</body>
</html>
navigation.html:
<div>
<p class="paragraph-inline">Welcome to the amazing navigation system!</p>
</div>
Ok, it's an simple example, the jist of the matter is that at the moment the navigation.html is rendered entirely before being inserted into the page. This means the css is not being called and can only be called if I include the css within the html blob.
I would prefer not to include css into every blob (footer, header, etc...)
So how can I force the site to load the html and apply the styles afterwards? I only want one css link at the top of the main page.

Your navigation should be .php as well. I'm not sure if there are options as far as syntax, but I write it like this <?php include("whatever-partial.php"); ?> This has never been an issue for me. I usually make a head.php with the boring stuff, and then include that in the header.php - and then an index.php - which pulls in header.php and footer.php for example. The server reads all that php - and spits out an html page that is served to your browser and applies the styles. It's not dynamic.

Make sure your include is a php file - then it will be inserted into the page before the browser gets ahold of the page and renders the css. Should be simple as that.

Related

Can PHP's require be used to require the head and body at the same time?

Is it possible to use PHP to include the contents of the <body> on one page, and add it to the <body> of the other page, while doing the same thing for the header? Or is it just easier / better to use two pages? This is kind of what I'm going for:
Some Page
<html>
<head>
- nav.php's header -
- stuff special to Some Page -
</head>
<body>
- nav.php's body -
- content special to Some Page -
</body>
</html>
I know the require statement can be used to take the whole contents of a file. Is there some sort of "merge" statement to kind of merge the pages together?
You are going to run into all sorts of security, re-use and maintenance issues if you rely on the inline behaviour of included files in PHP. But if you stick to some simple rules you can avoid these problems:
Any HTML tag opened by PHP must be closed in the same scope (i.e. function)
Included files must only contain namespace, constant, function and object definitions or further include/require statements (but using the autoloader is prefereable).
So applying these to your base page above, and observing the established good practice of putting includes/requires at the top of your page....
<?php
// always start your page with a PHP block - it makes interfering with the headers
// much less painful
require_once('nav.inc.php');
function local_head_content()
{
...
}
function local_body_content()
{
...
}
?>
<html>
<head>
<?php
nav_head_content();
local_head_content();
?>
</head>
<body>
<?php
nav_body_content();
local_body_content();
</body>
</html>
But it would probably be better to invoke local_head_content() / local_body_content() as callbacks from nav content.
(yes it is possible to do what you ask, even without function calls - but it would be a very bad idea which is why I've not explained how to do this).
A more conventional approach to solving the problem of shared content across different files is to use a front controller pattern - instead of the webserver selecting the page specific content, this is done in the PHP code with all URLs pointing to the same entry script.
Since you are including nav.php in the <body> of index.php, nav.php should not contain tags like <html>, etc. since that will result in a final page which does not conform to the HTML spec.
Using your example, this is the contents of the index.php page which will be received by the browser:
<!DOCTYPE HTML>
<html>
<head>
<title>Title</title>
<style>
- styles for index.php -
</style>
</head>
<body>
<!DOCTYPE HTML>
<html>
<head>
<style>
- Style for navigation menu -
</style>
</head>
<body>
<h1>Title</h1>
<nav>
- Navigation -
</nav>
</body>
</html>
<content>
- content here -
</content>
</body>
</html>
As you can see, your final page contains multiple <!DOCTYPE> tags, multiple <html> tags, etc.
nav.php should contain only the tags which you want to be included in that part of the final page. So your nav.php should look more like this:
<nav>
- Navigation -
</nav>
As for your styles in index.php, you should have a <link> tag which pulls in an external style sheet, e.g. <link rel="stylesheet" href="style.css">. All the CSS for all pages would go in style.css.

How to append to <head> with PHP in the middle of the page?

I have an HTML "chunk" of code with HTML and JS in it so I could easily include it with PHP. I also want it to have CSS styling but according to standards you are not "allowed" to do that - while it works it makes the page invalid. CSS is only allowed in <head> and not in the middle of the page (not untill HTML5.2 at least). So I thought about appending similarly named but separate .css file in the head, but with PHP and not JS (for performance sake)
<head>
<!-- PHP needs to include button.css here AFTER $App->INC("button"); has been called -->
</head>
<body>
<?php
$App->INC("button");
//This basically does 'require_once("button")';
//What do I need to add to the INC method to include css file in the head?
//Similar to $("head").append() but with PHP
?>
</body>
css file with the same name should be added to a <head> section.
PS:
This may seem as a design flaw and may as well be but here is the thought behind this.
I have a piece of code that when included in the right place of the
body generates a "loading screen" (or other UI elements that
can't/shouldn't be nested anywhere else but in the <body> of
the website.
It's got styling in a separate file
I send it to other user
They include it with a method of an "App" class which only does two
things: includes the file itself and css file nearby
Then they only use 1 line of code to put it where they want it and
not in 2-3 other places so the code is more manageable
Example:
You may try this:
<?php
ob_start();
$App->INC("button");
$button = ob_get_clean();
?>
<head>
<!-- Do your inclue here -->
</head>
<body>
<?= $button ?>
</body>
You can put the ob_start() / ob_get_clean() stuff inside button.php and return the content via your INC() method. Then you can save the content directly into $button like this: $button = $App->INC("button");.
But your example looks like a design problem. However I hope this will do the trick.
This could be a possible redesign:
<?php
$App->loadModule('button'); // Loads the module, the module registers stylesheets and content.
$App->loadModule('another_module'); // Load more modules ...
<head>
<?php $App->renderModuleStylesheets(); ?>
</head>
<body>
<?php $App->renderModuleContent(); ?>
</body>
If you include the CSS directly in the component itself, or expect the component to dynamically load the relevant CSS, then it could be quite difficult to maintain or customize. I am not saying you shouldn't go this route but be careful about asking your components to do too much.
A hook system as pointed out in the comments is one way to handle this.
Another simple way is to provide default styling which users can override. This is probably the simplest way to allow different styling for each component.
<head>
<!-- Provide some defaults. Users should not customize this one. -->
<link rel="stylesheet" type="text/css" href="default.css">
<!-- User's can customize this file to override the default styling.-->
<link rel="stylesheet" type="text/css" href="custom.css">
</head>
<body>
<?php $App->INC("button"); ?>
</body>
button.php - is only responsible for rendering a button. The separate CSS files will actually style it.
<?php
echo <input type"submit" class="button" value="Submit">
default.css - applies default styling
.button {
color: blue;
}
custom.css - overrides the default styling
.button {
color: red;
}
Final note, you may also want to look into using a main template file which sub-views inherit. This helps to reduce the number of full HTML files which link to your CSS files. The idea is to have 1 (or a few) template files that views inject themselves into. Here's some pseudo code.
frontend.php
<html>
<head>
<!-- Links to CSS files here. -->
</head>
<body>
<?php $placeholder('body'); ?>
</body>
Login.php
<?php inherits('frontend.php')->body; ?>
<form id="login">
...
Register.php
<?php inherits('frontend.php')->body; ?>
<form id="register">
...
About-Us.php
<?php inherits('frontend.php')->body; ?>
<p>About Us</p>
...

How to properly link CSS files with PHP footer and header

So I've recently discovered how to use php includes to include a footer and header in each of my files to avoid copy pasting all the header/footer code to each file. But let's say I have a footer.php, header.php, home.php, and about.php
Do I have my title, opening html/body tag, etc. in the header.php or home.php and about.php.
//header.php
<html>
<head>
links to header.css
links to home.css
links to about.css
</head>
<body>
//home.php
<?php include("header.php"); ?> //PROBLEM: the header.php also includes other .css such as "about.css", etc. that could result in problems later.
</body>
</html>
What Should I do to fix this? One way I thought of is to remove the beginning part(html,head,title) of the header.php file and move it home.css and about.css so they each have their own css links.
You're on the right track. Break out the stylesheets as well as the javascripts into other php files and include them as well. So all pages have the following structure.
home.php
<?php $this_page = "home.php";
include "template.php";
For other pages, just replace the $this_page variable. The structure common to all pages is actually the template.
template.php
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<!-- CSS-->
<?php include "stylesheets.php" ?>
</head>
<body>
<!-- common header -->
<?php include "header.php" ?>
<section>
<!-- PAGE CONTENT HERE determined by $this_page value -->
<!-- 'content_home.php', 'content_about.php'... have the content-->
<?php include "content_$this_page" ?>
</section>
<!-- common footer -->
<?php include "footer.php" ?>
<!-- link javascript files -->
<?php include "scripts.php" ?>
</body>
</html>
The only thing that changes from one page to the next is the value of $this_page. It's what determines which content gets loaded in the template above, and it also determines which CSS and JS files to include.
stylesheets.php
<?php
$cssDir = "path/to/styles/"; //folder where all CSS files live
//Link each page to its CSS file
$styles = [
'home.php' => 'home.css',
'about.php' => 'about.css',
'contact.php' => 'contact.css',
];
?>
<!-- CSS common to all pages -->
<link rel="stylesheet" type="text/css" href="<?="$cssDir/common.css"?>>
<!-- CSS, specific to the current page -->
<link rel="stylesheet" type="text/css" href="<?="$cssDir/$styles[$this_page]"?>>
The same approach can be used with the javascript you link to in scripts.php. Now that your HTML is into discrete modules, it is easy to edit a part of your site without worrying about another part breaking. In particular I recommend never to open a tag in one php file and close it in another because that would be a nightmare to debug, maintain and modify as your site gets bigger.
About paths:
Remember that when the browser sees the page, in place of include "stylesheets.php" and include "scripts.php", it will see the echoed contents of that file exactly as they are. So in those files you want your path to be either:
absolute paths from your domain root (simplest)
relative paths from the location of the top-level php file (eg home.php)
just the file name, if it is located in PHP's include PATH (places where PHP looks for content by default before throwing an error)
For header and nav you have to create a seperate file like nav.php which will contain only the nav and your site header not <head></head> and include it after your header.php. LIKE
//Home.php
<?php
include("header.php"); this will contain your head part mostly your .css and .js files
include("nav.php"); This will only contain header and nav
// home.php code goes here
?>
Also use below code will automatically get path to your root.
<?php
$PATH = "http://localhost/Folder/"; // change this when needed
$PAGE = basename($_SERVER['PHP_SELF']);
?>
Then Add your files like this
<link rel="stylesheet" href="<?php echo $PATH; ?>assets/plugins/font-awesome/css/font-awesome.css">
the bottom line is your code being accessible & easy to maintain, I would have a head.php, header.php & footer.php file. In the head.php you may want to include your config.php if you are connecting to a database & also have all the <html><head><title><link><script> tags you will include in every page then on your index.php or home.php
include('head.php');
include('header.php');
etc etc

Handling page-specific JavaScript in PHP header files

When designing a website in PHP, you typically have a header.php file that you include in every page on the site. The header.php file would include the <head> tag (among other things). However, I often find that I need to put page-specific JavaScript within the <head> tag.
The way I've handled this in the past is by adding IF statements to my header to determine what pieces of JavaScript should be outputted (i.e. IF this is the home page, output the JavaScript needed for the home page, IF this is the about page, output the JavaScript needed for the about page, etc.).
This is probably a terrible way to do it. What is the standard practice?
Well, first of all, <script> tags do not need to be located in the header. It's perfectly valid to put them anywhere in the HTML document.
But if you're determined to include them in the header, a simple solution is to declare a variable that the header should echo which contains your script tags. For example:
<?php
$scripts = "<script src='script.js' type='text/javascript'></script>";
include("header.php");
?>
And then your header.php script would like as follows:
<html>
<head>
<!-- header stuff goes here -->
<?php /*echo out scripts */ echo $scripts; ?>
</head>
<body>
<!-- part of body goes here -->
Assuming you are actually including header.php in every file, just define an array before you include header.php and add the extra scripts to that. Then in header.php, have it check for that array and write out extra script tags if necessary:
mypage.php:
$extra_scripts = array('jquery.js','jquery-ui.js');
include('header.php');
// Rest of your code.
header.php:
if (is_array($extra_scripts)) {
foreach( $extra_scripts as $script ) {
// Render a script tag
}
}
If you use a templating engine like Twig, you can inherit a base template as opposed to including a header and a footer and modify the 'blocks' defined in that base.
For example purposes, your base template might include a content block and a header_javascript block like so
{% block header_javascript %}
<script src='/js/jquery.js' type='text/javascript'></script>
{% endblock %}
Then, in your child template, you can override this block, call {{ parent() }} and then add your additional, page-specific scripts.
I can see that your question has been answered very clearly. but I would like to add something.
Well, technically, it is valid to place you script tag anywhere in your document but it is better to place your script at the end of document, unless necessary. it will let visitor still see your html and javascript yet to be download, and BTW normally you don't need to run you script until DOM is ready.
This is how I do it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta name="description" content="Page Description" />
<!-- Includes header stuff, css, js, google analytics, etc.. -->
<? include('header.php'); ?>
</head>
<body>
...
This allow me to avoid repetitive coding while adding flexibility to my pages.

Correct link rel CSS stylesheet not being implemented for a menu

I have menu.php, and in the <head> section of menu.php, I have menu.css as a link rel tag of course, both of which work perfectly fine.
Since menu.php is a 'menu', I've required it on pages that need a 'menu' in order to navigate around the website. However, whenever I require menu.php on a page that has its own CSS stylesheet, menu.php inherits the <body> font-size of the other stylesheet.
Here is what I'm trying to say: So if I require menu.php on profile.php, menu.php elements will become the size of profile.css, instead of what they really ought to be(menu.css). How can I fix the following problem? Currently, I am requiring menu.php BEFORE the <html> tag.
Should I put this within <head>? Somewhere else?
Thank you.
Some of the code from menu.php:
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu.css" />
</head>
<body>
</body>
</html>
I've put my PHP code before the <html> tag in the file above.
The below code comes from main.php:
<head>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
If I understand you correctly, you include a complete html page generated by menu.php before the html in main.php. That would get you 2 <html> sections, 2 <body> sections, etc. in one document. That should lead to lots of trouble.
You should include your menu in for example a div inside the main page like (just an example):
main.php:
<body>
<div id="nav">
<?php require 'menu.php'; ?>
</div>
...
</body>
and put all menu styles in the main style-sheet, pre-fixed with #nav. Or as a separate style-sheet, but still pre-fixed with #nav (every style) so that they overwrite the main document's styles.
Could you paste the content of your menu.php? Because if there are and section there...you're doing it wrong, because in that way you're going to have two head and two body parts. Think for require in php as copy and paste.
Your options:
Migrate to some template system(as Smarty for example).
If there should be menu.php on each page, why not putting this css as static file in the header
Paste some code, so we could help you easier ;)

Categories