How to include CSS in header with PHP? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Lets say I have markup like:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
PutIntoHeader("<script src="im_on_top"></script>")
?>
</body>
</html>
The PutIntoHeader function would put the given script into the head section of the html which is rendered. I might be missing something really obvious, but I cant seem to figure that out. Any ideas how the function would be able to do that?
The output would be:
<!DOCTYPE html>
<html>
<head>
<script src="im_on_top"></script>
</head>
<body>
</body>
</html>
Thank you for any ideas.
Edit:->
Hi, I feel like a noobie getting this kind of answer:) My system is highly complex and in the time I write header I dont know which scripts will get requested for that particular page as its all dynamic. I could put all html in variable before it gets rendered and then traverse it as xml and put it there manually while storing the scripts in an array but I dont want to go this road.

In almost all situations you can simply get away with combining and minifying you scripts into a single file. This slows down the initial loading time (first visit of site), but will speed up further visits / navigation because the file will be cached.
Of course YMMV and it depends on your specific situation. See for example this thread.
There is also the thing that user agents cannot do unlimited concurrent connections to the same domain to load resources.
See for example these two (somewhat outdated) benchmarks:
What's the maximum number of simultaneous connections a browser will make?
Max parallel http connections in a browser?
In the comments you said you are working with a million different widgets. Does this mean that these widgets all have completely specific and different code or is just the data different or presented differently? If it is just data / presentation you don't need different script for that.
If indeed you are talking about a million completely different codes for the different widgets (a million suddenly sounds like a made up arbitrary number) it indeed may make sense to not load everything in a single script. But this is impossible to answer by us, because it depends on the filesize, how fast you want to load the first visit, how many shared code it has and more numbers like that.
So to get back to your questions "How can I load specific scripts in the head?".
One option would be to not render it in the head, but place it just before the </body> and body tag instead. The advantage of this approach is that you know what script to load by then. The pages will load faster (because resources in the head will be first downloaded in full before the actual page is ever going to be rendered). The drawback of this approach is that there is a small latency before your script will kick in because it will be last thing that gets loaded in the DOM.
Another option would be to defer the rendering of you HTML on the PHP side and using it more like a templating engine. A simple example of this is by first getting all the widgets you want to display and only after you have done this start the HTML rendering in PHP.
some bootstrap file
<?php
// load widgets from db or wherever
$widgets = [
[
'template' => '/templates/widget1.phtml',
'script' => '/js/widget1.js',
],
[
'template' => '/templates/widget2.phtml',
'script' => '/js/widget2.js',
],
];
require __DIR__ . '/templates/page.html';
some template (page.phtml)
<!DOCTYPE html>
<html>
<head>
<title>My page with widgets</title>
<?php foreach ($widgets) { ?>
<script src="<?php echo $widgets['script']; ?>"></script>
<?php } ?>
</head>
<body>
<?php foreach ($widgets) { ?>
<?php echo $widgets['template']; ?>
<?php } ?>
</body>
</html>
P.S. in the above example I have used script tags, but it could also be expanded for css files also obviously.

If you don't want to put it directly in the head because at the time you don't know what's going to be needed, you need to carry out the logic beforehand.
You need to separate the logic from the view and have the view as a simple way of rendering your information.
First calculate everything about your page and leave yourself with variables which you can use to extract relevant information, then output the relevant html for the variables you have calculated beforehand.
This could be done yourself in one page, or what I would suggest, is using some sort of library to help out with this. Something like Kohana is really good at this, you could use Kohana to separate out your controllers, models etc and then use something like mustache as a templating library. Mustache lets you create views with only the most basic of logic in them (the way it should be).

Your PHP code has no way to know where the contents should be output. PHP loses its control over the data once the page is rendered.
You seem to be trying to write the content in the <body> and then have it injected in <head> section. Why don't you output the content in the <head> section instead?
<!DOCTYPE html>
<html>
<head>
<?php echo "<script src=\"im_on_top\"></script>"; ?>
</head>
<body>
<!-- Some HTML markup here -->
</body>
</html>

You may try something like this:
<head>
<?php echo '<link rel="stylesheet" type="text/css" href="theme.css">'; ?>
</head>

Related

Edit Entire Site With One Code/Page?

As the title says, is there a way to edit a portion of an entire site with one code or page? For example, if the bottom of every page of a site said "2014", is there a way in html or css to change every page of the site to say "2015" without having to do so manually to each individual page?
I understand this can be done in php, and I understand that a server can be configured for html to read php code. Are there any flaws to this method (perhaps the html page will load slower if it's configured to read php)? Are there any other ways to do this besides using php code?
Performance Concern:
You will not see any performance difference between having PHP render basic HTML and typing the HTML yourself.
The performance impact is only noticeable on HUGE PHP applications. And even then, it's still very fast.
What you ask is common practice. This is an example of what you can do.
Make a file called index.php and put this inside:
<!doctype html>
<html>
<head>
<!--Your head stuff-->
</head>
<body>
<header><?php require_once 'header.html' ?></header>
<section class="main_content"><h2>My Page!</h2></section>
<footer><?php require_once 'footer.html' ?></footer>
</body>
</html>
Make a file called header.html and put this inside:
<h2>This is my header</h2>
Make a file called footer.html and put this inside:
<h2>This is my footer</h2>
As you can see, the practice is to use any of the built-in PHP functions to include other files in your PHP file:
include 'some_file.php';
require 'some_file.php';
require_once 'some_file.php';
I think Dreamweaver can do this, with its find and replace entire website property
Assuming all pages have a CSS file in common, you can use the content CSS property of a pseudo element like before or after to control content across all pages.
For example:
#footer:before {content:'2015';}
<div id="footer"></div>

Web Design; Same Object on Multiple Pages?

I apologize of this question has been asked before. I tried searching around, but was unable to find a relevant answer (probably due to my relatively small "web-design vocabulary").
I've noticed that the majority of websites have at least one--if not more--standard "objects" (or whatever the actually name is for them) on almost all of their pages. For instance, Stack Overflow has the same logo and tabs (Questions, Tags, Users...) on every page. I'm assuming that there's a less painstaking way to set this up other than simply copying and pasting the same code over and over, especially when ease of modification becomes a factor. As far as I know, CSS can't do accomplish this level of style generalization, so I'm assuming a server-sided language like PHP is part of the equation.
I'm not really looking for a very specific answer. What language--or type or language--as well as a brief synopsis of at least one way to achieve some sort of "object pasting" will be sufficient.
Like others said, this is a major reason why people go from HTML to something like PHP, at first just to split up parts of your page.
Yes, you can do exactly that. What I usually do (if I'm not using a framework) is create a folder in my directory like this:
inc/header.php
inc/footer.php
inc/menu.php
index.php
Then in index.php you'd need an include like:
<? include('inc/header.php'); ?>
<h2>Welcome to my site</h2>
<p>We're happy to have you</p>
<? include('inc/footer.php'); ?>
And in inc/header.php:
<!DOCTYPE html>
<html>
<head>
<title>My site</title>
</head>
<body>
And in inc/footer.php:
<div id="footer">
<h2>Thanks for visiting</h2>
</div>
</body>
</html>
And so on for inc/menu.php
Then for other pages on your site, do the same includes for header, footer, and menu, and just write your page-specific content between the includes
Just an alternative to PHP:
Use Javascript or jQuery.
$( "#footer" ).load( "includes/footer.html" );
Another alternative is to use SHTML, which is basically HTML with inserts.
An easy way to do this is to create separate files for different sections of your page then instead of pasting the same code on each page use
include ('yourfilename.php');
to add the code in yourfilename.php at that point in the php file. This also makes it easy to modify that section and have your changes be reflected on all the pages that use yourfilename.php
For example, you can make one file called page_top.php and another called page_bottom.php. Then on each of your various php pages you can include('page_top.php'); near the top and include('page_bottom.php'); near the bottom. The code within these files will then be executed on each of your content pages.
There are of course other methods but this is a super easy way and you should look into this first.
An example of include would be:
header.php
<!DOCTYPE html>
<html>
<head>
<stuff><stuff>
</head>
<body>
<div id="mybanner">Design and logo that is common on all pages</div>
content/contact.php
<div id="bulk_of_the_html">
The rest of your stuff goes here
</div>
foot.php
<div id="footer_common_to_all">This is your footer content that is common to all pages</div>
</body>
</html>
To use would be something like:
contact.php
// This is your common to all pages header
include("header.php");
// This can be changed up as content switches
include("content/contact.php");
// This is your common to all pages footer
include("foot.php");
HTML imports or Webcomponents is a new way to do this completely at client side using HTML, JS and CSS. Write a component and reuse it in every page. But it uses ShadowDom, means not search indexable yet.
<link rel="import" href="header-banner.html">
<!-- use this in body -->
<header-banner></header-banner>
You have two solutions
Use include('....php') or require('....php') or include_once('....php') or require_once('....php') php functions to add external sections/modules into your web page(php).
You can call this functions at the position where you want the extremal module/part to be appeared.
include("Header.php"); // call to external module
// your body goes here
<h1>.......</h1>
<p>........</p>
.....................
include("Footer.php"); // again to another module
Or its better if you can go for a MVC framework where you can combine multiple modules and views into one output page...(ex Codeignitor/Cakephp...)

Is it okay to set title and meta description in php like this? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm setting page title and meta description dynamically on the pages of my site http://jobfou.com, since http is stateless, like this.
<html>
<?php
ob_start();
?>
<title> <!--TITLE--> </title>
<body>
Some HTML Page Content From Database Goes Here.
<?php
//The PHP Code Here Gets executed on each page loads, dynamically.
$wholePageContents = ob_get_contents();
$post_title = "Page 1";
ob_end_clean();
echo str_replace("<!--TITLE-->", $post_title, $wholePageContents);
?>
</body>
<html>
Is it okay to set page title and meta description like this, calling ob_start(); on each page load, what are the pros and cons, or should i just go with using jquery. Which is better, and doesn't consume memory.
Whether its OK, is partly opinionated and partly down to your specific situation. When i first started learning PHP many moons ago now, buffering the entire output into memory for post output processing seemed quite common, but it has the major pitfall of that it increases memory consumption.
For a small site this isn't going to be a big deal. Your not going to hit any script memory limits (its only text after all, you'd need a shed load of output to do that), and your probably not going to have that much traffic that freeing memory and memory per request are on your metrics (in fact, you probably won't even be monitoring any metrics if you're asking this question).
The second issue is particular to your example. What your asking PHP to do, is scan the entire text held in that variable, looking for a particular string and then replace it. This isn't particularly an expensive operation unless your str_replaceing a good few things, but it's not the best, ideal nor an advisable way to achieve what you want.
Think of PHP much like a str_replace function. It runs/executes BEFORE your HTML is outputted. So you can use PHP to place text inside HTML, before it gets sent to the user. Since we can do this, we can put PHP code inside our HTML, which will be run and in most cases print some HTML/text.
So let's look at your example...
Instead of inserting "tags" into your HTML to be replaced, we can put some PHP directly into the HTML
<?php
$title = "My first website";
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
Some stuff here...
</body>
</html>
And it doesn't just have to be one simple echo inside the HTML (don't forget the tags so the PHP interpreter knows that it needs to do something though). We could do something a little more fancy in our title tag...
<html>
<head>
<title>
<?php
if($_SERVER['PHP_SELF'] == 'index.php') {
echo 'My Website :: Homepage';
} else {
$pagename = array_shift(explode('.', $_SERVER['PHP_SELF']));
echo 'My Website :: '.$pagename;
}
?>
</title>
</head>
<body>
Some stuff here...
</body>
</html>
Here's a different way you could do using functions. Lets create a file called template_functions.php.
function header($title = 'Some default title', $meta_kw = '', $meta_descr = '')
{
?>
<html>
<head>
<title><?php echo $title; ?></title>
<meta name="keywords" content="<?php echo $meta_kw; ?>" />
<meta name="description" content="<?php echo $meta_descr; ?>" />
</head>
<body>
<?php
}
function footer() {
?>
<div id="copyright">Copyright MyWebsite <?php echo date("Y"); ?></div>
</body>
</html>
<?php
}
Now we have a bit of reusable code, so if we want to change the main header (i.e. add facebook javascript to every page), we can do it without editing every single script. So now we can create an index.php like this:
<?php
require_once("template_functions.php");
header("My Homepage", "Some keywords", "Some description");
?>
Enter site content here
<?php
footer();
?>
and a contact.php page like this
<?php
require_once("template_functions.php");
header("Contact US", "Some keywords", "Some description");
?>
Enter Your contact info, social network info, a map or a contact form here if you want!
<?php
footer();
?>
This should hopefully show you have to start mixing PHP with HTML and even have the added bonus of functions which allow you to re-use bits of code. Templating can get far more complex that this, but i don't want to blow your mind. Start small...
To finalise my very long answer, let's address the question put differently. Is it wrong to ever use tags in HTML and process them? The answer to this is NO. You must decide what works for you and your situation. Sometimes it's unavoidable, sometimes it's just a better way of doing things. However you usually find when you do require this sort of thing, it's on a much smaller scale of text (i.e bbcode parsers for a user comment, or replacing tags in email content that is saved in a txt file somewhere).
Hopefully this answer helps you out! Any questions we're here to help

Adding PHP to a static site. Not sure if my workflow is right

Let's try to explain the title of my question to be the more concise I can: I'm basically designing a static HTML website from scratch. Nothing to worry about here.
The point is that I'm trying to include some links that will retrieve some items (a product inventory) from a database (and therefore the site won't be so 'static' anymore), as there're > 300 products and creating an html for each one is not feasible.
After googling and reading several sites for days, the "easiest" solution I came up with is to use PHP and MySQL. Again, nothing to worry about. Just took my time for reading documentation and move along.
My question is more related about the correct workflow for integrating both worlds. Let's see my idea in code:
This is one schematic example of the page where you can browse some products (e.g: product.html):
<html>
<head>
<title>My Site - These are our products</title>
</head>
<body>
<!--Site goes here-->
Search by name
Search by color
<!--rest of site goes here-->
</body>
</html>
Where the links
product_search_by_name.php
product_search_by_color.php
are actually a modified clone of the same page (product.html). This is, keeping same html code, plus the .php code embedded into it, as I want to have the DB results displayed into a div on that same page, keeping exactly same layout.
So, am I doing this right if I want to maintain the appearance of the whole website? I'm absolutely wrong from the base and should start again? Should I give up and work selling frappuchinos on a Star*ucks?
As a sample of the idea I want to achieve is the following: http://www.w3schools.com/tags/default.asp (when you click on the left menu bar, the center zone updates with the content). By the way, are they using AJAX on that website to update just the center zone, or I'm misunderstanding what is AJAX for?
I'm sure I'm missing something but I'm too confused to separate the sheep from the goats, so I'd thank a lot any tips you can give to me (and additional documentation on the internets to read as well).
There are two main ways to merge or migrate from static HTML to dynamic HTML (PHP, PERL, whatever).
(1) One is to have most of the contest as HTML, and the stuff like inventory as dynamic.
<html>
<head>
<title>My Site - These are our products</title>
</head>
<body>
<h1>My Site - These are our products</h1>
<?php
// php code to retrieve links
?>
</body>
</html>
(2) To have a full PHP site.
<?php
echo "<html>" . "\n";
echo "<head>";
echo "My Site - These are our products"
echo "</head>";
echo "<body>" . "\n";
// php code to retrieve links
echo "</body>" . "\n";
echo "</html>" . "\n";
?>
Many developers start by merging both HTML & PHP.
I suggest to learn how to do a very simple but full php site, connect to a database, retrieve some records with a S.Q.L. query, display them as read-only text or links, and later you may change to the other HTML plus PHP way of doing things.
There are several editors and tools to help develop in PHP, specially by looking for a PHP function, or just highlight HTML tags. Scintilla (Linux) or Notepad++ in windowze, its a very simple yet useful tool.
Cheers.
Well, if you want it to make it using Ajax ...
You might want to do the following.
Create the two files as you said, those are not to be included in the HTML file.
Create a JavaScript function to call the files, You can use jQuery api, to link to php. http://api.jquery.com/jQuery.post/ or http://api.jquery.com/jQuery.get/
Link the click of the button inquired to call the JavaScript function, and add html you get from php to the tag you want.
You can create a index.php page and put down your html code in it. It looks like this
<html>
<body>
<!--- links goes here -->
Search Products
</body>
</html>
If you are retrieving products from a database and if you want to create multiple links for the products create a function in your function.php which pulls all the product name from the database. Now add this function into your index.php
index.php
<?php include ('functions.php')?>
<html>
<body>
<h3>Product List</h3>
product name
</body>
</html>
Always embed html in php file. Do not embed php in html file. File should have .php extension.

Creating a custom PHP template

I created a custom PHP templating system and the way I built it seems, well, inefficient. The three main goals for my template was to:
Pull all site-wide HTML elements from a template.tpl include.
Be able to dynamically assign content in the template.tpl (like <title> or <script>)
Be as efficient and scalable as possible.
In the end, my template system looked something like this:
randomPage.php
<?php
// declare any page specific resources
$pageTitle = "Random Sub-Title";
$pageResources = "/css/someRandomCSS.css"
$pageContent = "/randomPage.tpl"
// include the generic page template
include dirname($_SERVER['DOCUMENT_ROOT']).'/includes/template.tpl'
?>
randomPage.tpl
<h1><?=$pageTitle?></h1>
<p>Some random page's content</p>
template.tpl
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Site -- <?=$pageTitle?></title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link href="<?=pageResources?>" rel="stylesheet" type="text/css">
</head>
<body>
<? include $pageContent ?>
</body>
</html>
The main problem with this system is that for every web page, I need to manage two files: one for logic/data and the other for the page template. This seems largely inefficient to me, and doesn't seem like a very scalable approach.
Recently, I come across the smarty framework, which would allow me to consolidate my system from randomPage.php and randomPage.tpl into something like:
randomSmartyPage.php
{extends file="template.tpl"}
{block name=pageTitle}My Page Title{/block}
{block name=pageResources}
<link href="/css/someRandomCSS.css" rel="stylesheet" text="text/css">
{/block}
{block name=pageContent}My HTML Page Body goes here{/block}
Seeing this approach raised three major questions for me:
Are there any fundamental flaws with how I am approaching my templating system?
Can my original php code be refactored so I don't have to create two files for every web page?
Would using the smarty (or perhaps an alternative framework) be a good idea in this case?
Your code isn't really using any templating engine besides PHP itself, which is fine. A flaw I can see is your template will have access to all variables, and the ones you create for it are all global.
Two files is a good system, one to change what is preprocessed and passed to the view, and one for the view itself, containing HTML or whatever. This allows you to easily swap views, for example, a view for standard browsing and a mobile view for mobile browsers.
It can be a good idea, but I'm a firm believer that using PHP is good enough.
Here is an example, untested. It will encapsulate all the variables so you don't pollute the global namespace.
index.php
function view($file, $vars) {
ob_start();
extract($vars);
include dirname(__FILE__) . '/views/' . $file . '.php';
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
echo view('home', array('content' => Home::getContent()));
views/home.php
<h1>Home</h1>
<?php echo $content; ?>
The approach you are describing is part of MVC design pattern. Separating the different aspects of your application.
What you seem to have already understood is that PHP is a templating system in itself as have many others before you.
Take a look at this benchmark for a rough comparison of popular template systems.
Update 2022.08.29
Updated broken links to archived versions.
Note: The answer remains valid if you're trying to learn the language. But for anything serious, consider using a framework.

Categories