I have a php include statement for the "head" of my website.
I am using the following code to call head.php...
<?php
include '../components/head.php'
?>
And in my head.php I have the following code...
<head>
<link rel="stylesheet" type="css" href="/style.css">
<title>Dummy Code</title>
</head>
How can I make it change the title by having a variable in my page on my page like Dummy Code | About being the title if I have $title = "About" on my webpage.
Is there anyway to do this?
They all belong to the global namespace, so you just can do this:
<?php
$title = 'about';
include '../components/head.php'
?>
head.php:
<head>
<link rel="stylesheet" type="css" href="/style.css">
<title>Dummy Code | <?=$title; ?></title>
</head>
But make sure that you understand: this is very simplified code and should not be used on the production projects.
Related
First I had this:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
<title>PHP file</title>
</head>
<body>
<h1>
<?php
echo "Hi again...";
?>
</h1>
</body>
</html>
I accessed the file through localhost/learningphp/myfirstfile.php and it rendered properly, showing me a h1 element with the text "Hi again...".
Then I changed to this:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
<title>PHP file</title>
</head>
<body>
<p>
<?php
echo "Hi again...";
$myName = "Sahand";
echo $myName;
?>
</p>
</body>
</html>
Notice the change of <h1> tags to <p> tags, and the addition of myName. Still, when I go to localhost/learningphp/myfirstfile.php myName (Sahand) is not added to the page, and "Hi again..." is still shown in "h1 styling", like when I viewed the first version of the php file. Why is this and what can I do about it?
You will have two issues in this case may be
You are saving the file somewhere else or you didn't save the
updated content.
Your Browser history try a hard refresh by using Ctrl+F5 (for windows) Keys
together
I'm getting weird results when trying to kind of make a "templating engine". Basically, I want to be able to use PHP variables that contain data from an SQL database.
What happens is that everything works properly with the PHP side, what does not is the page that needs to display this information (index.php).
I'm working on a way to get the website's name from the sql database, so I have something like that on my index:
<?php
include ('php/data/sitename.php');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $sitename; ?> - Home</title>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<!-- HEADER: Navbar -->
<?php $navbar; ?>
<!-- MAIN: Index Page contents -->
<?php $page_index ?>
<!-- FOOTER: Footer -->
<?php $footer; ?>
<?php $sitename; ?>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>
This variable comes from a file (that has been included) called sitename.php, with the following code:
<?php
include ('../db.php');
$sql = "SELECT id, sitename FROM GeneralData";
$getname = mysqli_query($conn, $sql);
if ($getname->num_rows > 0) {
while($row = $getname->fetch_assoc()) {
$sitename = $row['sitename'];
echo $sitename;
}
}
?>
Yes, I used echo $sitename;, I know it wont echo the actual data, but I did it to test some things, and here are the results:
Including the file sitename.php to index.php will do nothing, it would be like if it did not exist. However, if I write "echo "123";" on it, it will echo 123 on index. What does not work is what I need.
If I go to sitename.php directly, it will simply output the correct SQL value I requested because I told it to echo (as I stated before). But, it wont work in index, it will simply not work.
Also, I'll leave my project structure here. It might help.
What can I do?
Thanks in advance!
try set GLOBAL for sitename
GLOBAL $sitename;
or
GLOBALS['sitename'];
$sitename = ...
EDIT
try use
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/yourpath/yourfile.php";
include_once($path);
I would like to give a title to each of my pages, but all my pages are linked to my index.php:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Test</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php include("top_bar.php");?>
<?php include("header.php");?>
<?php include("container.php");?>
<?php include("footer.php");?>
</body>
</html>
Here is how my site is: http://prntscr.com/47nn7h
All my pages have the title I put for index.php, but how to add a title to a specific page (example, when I go to the page members.php)?
members.php:
<?php include "index.php";?>
Thanks.
Replace the existing <title> tag with this.
<title><?php echo $pagetitle; ?> </title>
in your <head> block.
Make sure that $pagetitle actually contains the desired title before you emit the tag. It's not clear from your question where these titles are coming from - you'll probably need some PHP right at the top of the page to set all this up.
.
You could use this method and add the
$pageTitle = 'Title of Page';
to your content page (i.e. member page)
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" />
I'm trying to make the whole <head> section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.
So here is the code:
index.php
<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>
<body>
.....
..
.
header.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
Obviously this doesn't work; how can I pass arguments to an included file?
Include has the scope of the line it's called from.
If you don't want to create new global variables, you can wrap include() with a function:
function includeHeader($title) {
include("inc/header.php");
}
$title will be defined in the included code whenever you call includeHeader with a value, for example includeHeader('My Fancy Title').
If you want to pass more than one variable you can always pass an array instead of a string.
Let's create a generic function:
function includeFile($file, $variables) {
include($file);
}
Voila!
Using extract makes it even neater:
function includeFileWithVariables($fileName, $variables) {
extract($variables);
include($fileName);
}
Now you can do:
includeFileWithVariables("header.php", array(
'keywords'=> "Potato, Tomato, Toothpaste",
'title'=> "Hello World"
));
Knowing that it will cause variables $keywords and $title to be defined in the scope of the included code.
index.php:
<?php
$my_header = 'aaaaaaaaaaaaaaaaaaaa';
include 'header.php';
?>
and header.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="shortcut icon" href="favicon.ico" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php echo $my_header ?> " />
<meta name="Description" content=" <?php echo $my_header ?> " />
<title> <?php echo $my_header ?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
It's not an ideal solution, but I understand it's your first steps in php.
PS. Your Doctype doesn't match the code. I've adjusted your header html to be XHTML.
You can't pass arguments to include, but it has access to all variables you've already set. From the include documentation:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
Thus:
index.php
<?php
$header = 'aaaaaaaaaaaaaaaaaaaaa';
include("header.php");
?>
header.php
<title> <?php echo $header; ?> </title>
Well marc, when you are using include, you can simply just set up a variable to use:
<?php
$var = "Testing";
include("header.php");
?>
In your header file:
<?php
echo $var;
?>
Allow your previously defined variables are usable in any include you have.
you are over thinking it
<?php
$header = "aaaaaaaaaaaaaaaaa";
include("header.php");
?>
::EDIT::
Decided I would add value
The included file will gain the scope of where you included it. So if you include a file INSIDE a function:
<?php
$get_me = "yes";
function haha()
{
include("file.php");
}
haha();
// And file.php looks like
echo $get_me; // notice + blank
?>
More over, you include the same file more than once to great effect.
<?php
$output = "this";
include("cool_box.php");
$output = "will";
include("cool_box.php");
$output = "work";
include("cool_box.php");
?>
And even use this to load templates that become part of a method in a class. So you can do something like:
<?php
class template
{
private $name;
function __construct($name)
{
$this->name = preg_replace("/[^a-zA-Z0-9]/", "", $name);
}
function output(array $vars)
{
include($this->name.".php"); // Where $vars is an expected array of possible data
}
}
$head = new template("header");
$body = new template("body");
$head->output();
$head->output(array("content" => "this is a cool page"));
?>
defining a variable as a pseudo-argument/workaround before an include() - as recommended by many - is a bad idea. it introduces a variable in the global scope. define a function in the included file instead to catch the arguments u want to pass.
This is good approach. I however would do it a bit inside out. Define a layout, a wrapper for your webpage and include your content file into it:
layout.phtml
<html>
<head>
... your headers go here
</head>
<body>
<? include $content ?>
</body>
</html>
Your content template file can look like this e.g.
content.phtml
<h1>hello world</h1>
<p>My name is <?= $name ?></p>
Then, you would have your main script (index) that will handle logic, connects to database etc.
index.php
$content = 'content.phtml';
$name = 'Marc'; //Can be pulled from database
include 'layout.phtml';
This way, you can nicely separate business logic and presentation. And it can help you cut repetitive code for parts of page like logo or navigation which are repeated on the whole site.
If you include a file it is just like inserting that code into the parent file. You could simply do this:
<?php
$parameter = "Hello World";
include("header.php");
?>
and then in the header.php
<?php
$parameter = isset($parameter) ? $parameter : "Default Text";
// Use accordingly
?>
I used the isset() method to verify that it has a value already and is instantiated.
I noticed nobody suggested using a template engine. I came looking here because for the project I'm working with, a template engine isn't possible and that might be your situation too, however I thought it might be worth mentioning these: Twig (my preferred engine) and Smarty both allow passing specific variables to includes.
I highly recommend the use of a template engine whenever possible, as it simplifies your front end code, adds a layer of abstraction between your front end and back end, and both Twig and Smarty automatically clean the variables you pass to them which helps mitigate XSS attacks.
Twig Example
header.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content="{{ header }}" >
<meta name="Description" content="{{ header }}" >
<title> {{ header }} </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
index.html
{% include 'header.html' with { 'header' : '<script>alert("this shouldnt work")</script>'} only %}
Body Text
{% include 'footer.html' %}
Smarty Example
header.tpl
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content="{$header}" >
<meta name="Description" content="{$header}" >
<title> {$header} </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
index.tpl
{include 'header.tpl' header='<script>alert("this shouldnt work")</script>'}
Body Text
{include 'footer.tpl'}