In my file index.php I have included this text from another file.
<title>
<?php
$title = "";
if (basename(__FILE__, ".php") == "index") {
$title = "Home";
} else {
$title = ucfirst(basename(__FILE__, ".php"));
}
echo $title;
?>
</title>
And I guess you can see what i does, and if not, then it's supposed to set the title to the basename of the file. So say you have a file called downloads.php, then the title with this script would be Downloads. But I have this problem which I don't know how to get past. When I include the text via.
<head>
include "filename.php";
</head>
And my problems is when I include the text, the 'script' runs before it includes. Say if the name of the file you included is filename.php and the main page where you have included the text is main.php, the header would be Filename and not Main. And the reason why I want to include the text, and not just paste directly into main.php is because it's much easier to edit if you have multiple files where you need the exact same code.
I hope you understand what I'm asking, and that you are able to help me.
Try $_SERVER['SCRIPT_NAME']:
if (basename($_SERVER['SCRIPT_NAME'], ".php") == "index") {
$title = "Home";
} else {
$title = ucfirst(basename($_SERVER['SCRIPT_NAME'], ".php"));
}
It looks like you're trying to set up a simple system for breaking your pages up into "subpages". Good idea. But rather than relying on the filename, why don't you set a variable? For example:
In page_title.php:
<?php
echo "<title>" . $title . "</title>";
In index.php:
<?php $title = "Home"; ?>
<head>
<?php include "page_title.php"; ?>
</head>
In some_other_page.php:
<?php $title = "Some Other Page"; ?>
<head>
<?php include "page_title.php"; ?>
</head>
And the same for any other pages you want...
In fact, you probably want to encapsulate the whole <head></head> section of your page.
Finally, rather than reinventing the wheel, you might want to look at some of the templating engines out there for PHP. I like Smarty, but there are others. These templating engines make it possible to write template files (including other template if necessary) and make it easy to simply pass variables to the template & render your HTML.
Related
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.
I have several files with a header and a footer, let's say file1.php, file2.php and file3.php
These files include() the files header.php and footer.php.
Now the concern is this... Each page has to load a general header content with certain css styles, but also a -specific- style for such page. This also happens on the footer: it loads a bunch of scripts for all pages, but a specific script for a specific page.
How can I achieve this?
I certainly don't want to put the specific script on the specific page because it might not only be attached to one, but several ones, the js script or the css style can be attached to five or ten pages...
I was thinking a switch() for each case in the header or footer page, then any conditional (such as $_SERVER['PHP_SELF']) in the other pages, but how can I do the include thing? is it include() what I'm looking for?
Thank you.
This is pretty much beyond the scope of Stackoverflow but why not.
Switch inside the template
I see you added that you were thinking of using a switch. Here is an example of something simple you could do.
header.php
<html>
<head>
<title>...</title>
<?php switch(basename($_SERVER["SCRIPT_FILENAME"], '.php')) {
case 'file1': ?>
<script src="file1.js"></script>
<?php break;
case 'file2': ?>
<script src="file2.js"></script>
<?php break;
}
?>
</head>
<body>
Just sample code in-between the case and break. This code initiates a switch on the file name, file1.php would be 'file1'.
Output Buffering
What else you could do is output buffering. Let's say you have a template at file1.tpl.php, then you have header.php. Inside file1.php, you could do this:
ob_start();
include "file1.tpl.php";
$content = ob_get_clean();
include "header.php";
Everything processed from file1.tpl.php will be stored in $content. Then inside header.php, you load $content where you see fit:
<html><head><?= $content ?></head><body>
A simple implementation might go like so:
Define a global styles array (say, in a config.php file that gets included on every page), which holds an array of CSS files that can be load:
global $styles = array(
"foo" => "/styles/foo.css",
"bar" => "/styles/bar.css",
);
with the value holding the path to the relevant CSS file.
At the top of the page in question, setup a variable to determine which CSS files to include:
$activeStyles = array('foo');
Then, in your header.php, check for the existence of the variable, and whether or not it contains any values:
<?php
if(isset($activeStyles) && count($activeStyles) > 0) {
# iterate through the array, generating the appropriate <link /> tags
foreach($activeStyles as $styleKey) {
?>
<link rel="stylesheet" type="text/css" href="<?php echo $styles[$styleKey] ?>" />
<?php
}
}
?>
You would use the same concept for scripts.
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.
I've been using headers to create templates for websites.
It's easy, and very convenient for debugging.
I now face the problem of using head BUT with custom page titles.
If this is my header.php >
<html>
<head>
<title> My Site : ??? </html>
</head>
<body>
</body>
</html>
I need ??? to be replaced for every page.
Is this possible? If so, how? Thank you. : )
Not knowing more about your file inclusion scheme, the simplest way would be:
page2.php
<?php
$pageTitle = 'Page 2';
include 'header.php';
?>
<div>My content</div>
<?php include 'footer.php'; ?>
header.php
<html>
<head>
<title> My Site : <?php echo $pageTitle ?> </title>
</head>
<body>
footer.php
</body>
</html>
webbiedave's answer is perfectly fine, but in the long run, you should really learn to use either a decent template language (Smarty, Twig), or a PHP framework that has it's own templating. Kohana and Codeigniter are both pretty easy to get into.
If i were to add some code before including the header, will it help?
<?php
$currentPage = "Random Page Title";
include "header.php";
?>
And then use the value in header.php so print the page title?
you could query a DB for the title of a page and then print it using php :)
Edit:
Looking back at the problem , depending on how you have your website designed this may not be the simplest solution. But if you are already using some sort of ID system this should be easy.
Yes, it will help definitely. But you need to do a little customization.
First of all, make sure that you connect to the database, if you want to query / fetch data from database. For this to happen, include the "config.php" page at the very beginning of the script, in which your database connection logic will be present.
Then, write your query to fetch data from that database, and assign that value to the required variable for using it in the header page.
Lastly, include your "header.php" page.
For "config.php" page:-
Logic of Database Connection, like using of "mysql_connect()" & "mysql_select_db()" functions.
For "custom.php" page:-
<?php
include "config.php";
$sql = "SELECT pageTitle FROM db_table WHERE condition = 'something'";
$sql_exe = mysql_query($sql) or die("Error in Fetching Page Title");
if( mysql_num_rows($sql_exe) ) {
$currentPage = mysql_result($sql_exe, 0, 0);
}
else {
$currentPage = "Random Page Title";
}
mysql_free_result($sql_exe);
include "header.php";
?>
Also, if you want, you can always use some class for mysql connection & queries, to fetch data. But this is how it always work.
you can call javascript to change the title of the page dynamically, this is a better solution if you have a master file index.php that calls all other includes
You could also use something like this:
if you married up your php filenames with your page titles
you could use explode or str replace to make it more user friendly to replace commas or underscores for example.
<?php
echo basename($_SERVER['REQUEST_URI']);
?>
or
<?php
// my_page_title.php
$var=basename($_SERVER['REQUEST_URI']);
$pagetitle=str_replace("_"," ",$var);
// my page title
?>
<title> My Site : <?php echo $pagetitle; ?> </title>
Corrected 1 small error in Webbiedave's header.php entry
</html> should be </title>
<html>
<head>
<title> My Site : <?php echo $pageTitle ?> </title>
</head>
<body>
I have a small situaton here. I'm building a custom CMS for one of my websites.
Below is the code for the main index page:
<?php
require("includes/config.php");
include("includes/header.php");
if(empty($_GET['page'])) {
include('pages/home.php');
} else {
if(!empty($_GET['page'])){
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>
The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.
The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.
What do I do?
You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.
First check input and determine on which page are you
If you know you are on the homepage, include something like includes/templates/homepage.php
Otherwise try to load the page from the database
If it worked, include includes/templates/page.php
Otherwise include includes/templates/404.php
Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.
Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.
Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.