I'm trying to create a function 'header' which will print html content (doctype, html, head, body, etc) - but when I'm looking in a site source, all of that stuff is in one line, not in a tree hirearchy...
public function header() {
print(
'<!DOCTYPE HTML>'
. '<html>'
. '<head>'
. '<meta charset="utf-8"/>'
);
And when I'm looking in the web source the output looks like:
<!DOCTYPE HTML><html><head><meta charset="utf-8"/>
I would like it to look more like standard html tree:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
How can I do that? What are the options ?
EDIT:
Some of You showed me an echo option - it works, but it looks really bad in a php file - like:
public function header() {
echo "<!DOCTYPE HTML>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
</body>
</html>
";
The most classic way, using echo :
echo '<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
';
see below methods for printing HTML inside PHP code block
FOR SHORT HTML CONTENTS
echo ' <div class="myClass"> Some Text here. Some text here </p> ';
FOR SHORT HTML CONTENTS WITH PHP variable concatenation
$myName='Optimum';
echo ' <div class="myClass"> My Name is '. $myName .' </p> ';
FOR LONG CONTENT
$html.='';
$phpVariable ='Dummy content'
$html.='<div class="wrapper">'
$html.='<div class="content">';
$html.='<p> My content here'. $phpVariable .' </p>';
$html.='</div>';
$html.='</div>';
echo $html;
According to your scenario
<?php
public function header() { // SOME NECESSARY PHP CODE ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="<?php //echo get_chartset ?>"/>
<link rel="stylesheet" type="text/css" href="<?php //echo_css_path ?>">
}
?>
This will echo/ print clean HTML code in front.
You could introduce tabs when you print:
print("<!DOCTYPE HTML>"
. "<html>"
. "\t<head>"
. "\t\t<meta charset=\"utf-8\"/>"
);
Another approach would be to simply just separate your html template file (Format it however you want) and then just require it with passed data in your function like so
my_view.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1><?= $heading ?></h1>
</body>
</html>
Your function
function showTemplate($view, array $data) {
extract($data);
require $view . '.php';
}
That way you can just call to output your view with data, like this
showTemplate('my_view', [ 'heading' => 'Awesome Page' ]);
This way your template and data would be more organized and pretty.
Another way, for doing this :
<?php
function myheader() {
?><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<?php } ?>
I redefined the function name to avoid conflict, (off-topic).
I don't know how such a code should be indented ...
Related
i want to parse title from pages code source using title tag, someone made this for me but i dont know whats the problem because its not working, pls if anyone can help i really will appreciate that.
thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title></title>
<?php
$url; = '';
preg_match("#<title>(.*)</title>#Ui", file_get_contents($url), $title);
$title = substr($title[1],0,255);
echo "Title $url : ' $title '<br>";
?>
</head>
</html>
You gotta fix this line: $url; = ''; to remove the semicolon after $url. Also, you should echo the result between the <title> and </title> tags, not after them. And lastly, a better structure for your application will be to execute PHP and then output HTML.
<?php
$url = ''; // <-- insert the URL of choice here, within quotes, starting with http://
preg_match("#<title>(.*)</title>#Ui", file_get_contents($url), $title);
$title = substr($title[1],0,255);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>
<?php echo $title; ?>
</title>
</head>
</html>
I would like to write a function to return a string with html code to customize head title, description and keywords for multiple pages. I started with my index.php file and two auxiliary, _head.php and _functions.php. What do I have to do to implement this function?
index.php:
<?php include "_functions.php; ?>
<html>
<?php echo make_head("My title", "My description", "My keywords); ?>
<body>
...
</body>
</html>
_functions.php:
function make_head(title, description, keywords) {
return file_get_contents("_head.php");
}
_head.php
<head>
...
<meta name="description" content="$description">
<meta name="keywords" content="$keywords">
<title>$title</title>
...
</head>
_functions.php:
function make_head($title, $description, $keywords) {
$head = include "_head.php";
return $head
}
_head.php
<head>
...
<meta name="description" content="<?php echo $description; ?>" >
<meta name="keywords" content="<?php echo $keywords; ?>" >
<title><?php echo $title; ?></title>
...
</head>
You can use include.
In your function make_head, you can do something like this:
function make_head(title, description, keywords) {
$html = include "_head.php";
return $html;
}
When you include something, it loads it to your current state. So if you use $title or $description or $keywords in your _head.php file, they will be in the same scope and they can be used.
This code has a number of vulnerabilities and including files like this is never a good idea. I can see this code is only entry level though and probably just for practice so to get this working you need to do something like the following:
<?php include "_functions.php; ?>
<html>
<?php echo make_head("My title", "My description", "My keywords); ?>
<body>
Then in your make_head function, return the HTML code
function make_head(title, description, keywords) {
return "<head>
...
<meta name='description' content=' . "$description" .'>
<meta name='keywords' content=' . "$keywords" . '>
<title>$title</title>
...
</head>";
}
This approach leave you open and I certainly wouldn't use it in production.
FUNCTIONS.PHP
<?php
function global_header($page)
{
echo "
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>" . $page . "</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>
";
}
?>
<?php
function global_footer()
{
echo "
</body>
</html>
";
}
?>
When I view my page source in chrome/FF I get the following source:
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Add</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>
</body>
</html>
It's indented by about 3 tabs. Is there a PHP strip function or something that can align it properly? I don't like my entire pages HTML being messed up.
My expected output is to not be indented.
The reason you are getting indented outputs is that you are echoing them like that...
Simply remove the indentaions from the echo statements to get rid of them
<?php
function global_header($page)
{
echo "
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>" . $page . "</title>
<meta name='description' content='BTI320 Assignment 2' />
</head>
<body>";
}
?>
<?php
function global_footer()
{
echo "
</body>
</html>";
}
?>
This makes your php harder to follow fut the output will be as you requested
Consider using a template engine. Direct output of HTML strings is considered bad practice.
If you don't want to use third-party template engines, you can anyway benefit from some simplified templating like this:
page.tpl template file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8' />
<title>{{title}}</title>
</head>
<body>
{{body}}
</body>
</html>
PHP:
// Loading HTML code that does not contain any undesired whitespace.
$code = file_get_contents('page.tpl');
// Replacing template variables with their values.
$code = str_replace(
array(
'{{title}}',
'{{body}}'
),
array(
'Example title',
'Page body'
),
$code
);
// Outputting resulting HTML code.
echo $code;
is it possible to embed this into html
if (empty($_POST['extras'])) {
$message .="<br /> No extras selected <br />";
} else {
foreach($_POST['extras'] as $extra)
{
$message .="<br />Extras: ".$extra."";
}
}
I would like to place the above php statement at the bottom of this html code.
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Booking System</title>
<link rel="stylesheet" href="css/bs-admin.css" type="text/css" />
</head>
<body>
<noscript>
<div class="js_error">Please enable JavaScript or upgrade to better browser</div>
</noscript>
<div id="index">
<h1>Thank you for your reservation!</h1>
<p>
<h3>Your Booking is as follows:</h3>
<p>Dear <b><?php echo $custInf[0] ?></b>,
<p>You have Booked: <?php echo $eventInf[0] ?>
<p>Booking Date: <?php echo $eventInf[2] ?>
<p>Booking descriptiong: <?php echo $eventInf[1] ?>
<p>Number of machines booked: <?php echo $qty ?>
<p>Street: <?php echo $comments ?>
<p>Suburb: <?php echo $suburb ?>
<p>Postcode: <?php echo $postcode ?>
<p>Dropoff: <?php echo $dropoff ?>
<p>Duraton: <?php echo $duration ?>
If it's got php code in it then it's no more HTML.
You have to call it .php or .phtml.
PHP generates, or outputs html.
You can have pure html in .php scripts (outside the <?php ?> tags), but not the other way around (i.e. no php code in regular .html files).
If you want to add some logic (the PHP code) within it, you need to have it parsed by a webserver which will, in turn, generate 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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Booking System</title>
<link rel="stylesheet" href="css/bs-admin.css" type="text/css" />
</head>
<body>
<noscript>
<div class="js_error">Please enable JavaScript or upgrade to better browser</div>
</noscript>
<div id="index">
<h1>Thank you for your reservation!</h1>
<div>
<h3>Your Booking is as follows:</h3>
<p>Dear <b><?php echo $custInf[0]; ?></b>,</p>
<p>You have Booked: <?php echo $eventInf[0]; ?></p>
<p>Booking Date: <?php echo $eventInf[2]; ?></p>
<p>Booking descriptiong: <?php echo $eventInf[1]; ?></p>
<p>Number of machines booked: <?php echo $qty; ?></p>
<p>Street: <?php echo $comments; ?> </p>
<p>Suburb: <?php echo $suburb; ?></p>
<p>Postcode: <?php echo $postcode ?></p>
<p>Dropoff: <?php echo $dropoff; ?></p>
<p>Duraton: <?php echo $duration; ?></p>
</div>
<?php
$message = "";
if (empty($_POST['extras'])) $message .="<br /> No extras selected <br />";
else
{
foreach($_POST['extras'] as $extra)
{
$message .="<br />Extras: ".$extra;
}
}
echo $message;
?>
</div>
</body>
</html>
I think you're needing to create an empty variable $message before you could start appending "extras" to it. Then all you need to do is echo $message.
Yes you can, however that's not a good way to do it. You should go for the Model-View-Controller model. It separates the HTML code from the actual code that does processing. Many PHP Framework does this. (Though personally i find them too clunky and wrote my own)
Also, embedding HTML into PHP is bad, as again, code should be separated from the HTML by as much as possible.
Example of views and controllers (From my framework):
Controller:
class Controllers extends BaseController{
function index($args=array()){
// process data
$this->render('index', array('data1'=>$data));
}
}
View:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My site</title>
</head>
<body>
<h1><?php echo $page->data1; // echos out $data from the view ?></h1>
</body>
</html>
This is much cleaner than your model of embedding php into the HTML and/or vice versa.
Take a look at frameworks, they are usually pretty helpful, although PHP frameworks are generally very restrictive as to what you can do.
Yes, you can do what you are asking. Make sure the extension is recognizable by the php interpreter (usually .php)
If you need to hack something up quick, this is ok. But for anything else than that, look into using some sort of templating language. This becomes an important point because you want to seperate your logic from your display for the sanity of yourself and other developers that will work on your code in the future.
edit: oh, also very important. Don't use $_POST this way without sanitizing the data. It's ripe for XSS injections.
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Booking System</title>
<link rel="stylesheet" href="css/bs-admin.css" type="text/css" />
</head>
<body>
<noscript>
<div class="js_error">Please enable JavaScript or upgrade to better browser</div>
</noscript>
<div id="index">
<h1>Thank you for your reservation!</h1>
<!--- bunch of stuff omitted here -->
<?php
if (empty($_POST['extras'])) {
echo "<br /> No extras selected <br />\n";
} else {
foreach($_POST['extras'] as $extra)
{
echo "<br />Extras: ".$extra."\n";
}
}
?>
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'}