Tutorial: Building a Dynamic Website with PHP


Introduction to PHP

				<?php
?>

PHP (Hypertext Processor) is a server-side scripting language used to produce dynamic web pages. Formally known as Personal Home Page, PHP was first introduced as a platform for web development in 1995. PHP was one of the first server-side scripting languages developed to process data without the use of external files. It can be embedded directly into an HTML source document, and processed server-side before being displayed on a web-browser. PHP is open source and completely free software released under the PHP Licence.

PHP is one of the most commonly used scripting languages used for web-design today, and for good reason. Unlike HTML, content can be dynamically loaded using PHP includes that grab data from a multitude of files and parse them into one document, which is what the web-browser receives from the server.

While HTML is relatively easy to learn, PHP is considerably more sophisticated and demanding to learn from scratch. It is highly recommended to learn HTML, before jumping into PHP. This tutorial assumes you have at-least a basic understanding of HTML.

What you will need

A good text editor is essential for website design, do not try to build your website in Notepad, there are dozens of programs available to help you. If you are new to web-design, I do not recommend jumping straight into Dreamweaver. Dreamweaver is an advanced web-design software suite, and will be far to convoluted for beginners. I highly recommend using Notepad++ for Windows, as it supports most web languages, as-well as many others.

As mentioned previously, PHP is processed server-side. This means that unlike HTML, software is required on the server to process the data. There are several available software packages that will work, however I highly recommend XAMPP. Multiple distributions of XAMPP are available from the Apache Friends website, including Windows, Mac, Linux and Soloris. Install your distribution and open the XAMPP Control Panel. This allows you to enable & disable services on your server. Start Apache and navigate to the htdocs folder within your installation (can be found by clicking Explorer within XAMPP Control Panel). This is the directory in which you will be working on your new website.

You can test your new Apache server by opening your web-browser and navigating to http://localhost/xampp/


Once you have confirmed your server is up & running, go ahead and delete all the files within the htdocs directory (don't worry we don't need them any more). Now you're ready to start building.

Download Notepad++
Download XAMPP

Get-up-to date with HTML5

Before you begin, it is worth considering brushing-up on your HTML skills. HTML5 has introduced a lot of new functionality that may just save you a lot of time later-on. All major web browsers now support HTML5, and most older browsers are "backwards-compatible", so there really is no sense making a new site with old semantics. If you want a quick HTML5 catch-up lesson, see this article.

Set-up your file structure

In-order for your new website to be dynamic you are going to need a dynamic file structure. There are numerous ways you could organise your file structure, some more complex than others. Once your website becomes large enough, you may find yourself with dozens if not hundreds of separate files in one location, we want to avoid this as much as possible. For this tutorial, we will be looking at adapting your HTML knowledge with PHP, so forget using .html files for every page.

You are going to need a directory for your PHP includes, you may call this directory anything you want, but let's try to keep it simple for now, create a folder in htdocs named "theme" (lowercase). More can be added in this same manner later-on, but for now this is all we need.

A note about .htaccess

Apache based servers can be configured to perform certain tasks before processing any actual data on a page, this is done by including a file named .htaccess within the root directory of your site. There are a lot of things you can do with the .htaccess file that you will find to be very useful later-on, but for now we only need to set one option. Open your text editor and create a file named ".htaccess", and add the following line:

				DirectoryIndex index.php

This tells the sever to use the file named index.php as the index page for your site.

Why can't I use .html / .htm files?

You can. PHP does not process directly from .html / .htm files by default, but you can change this by including this within your root .htaccess file:

				AddHandler application/x-httpd-php .html .htm

This tells the server to treat all .html / .htm files as PHP code, thereby allowing the use of PHP includes directly within the .html source. We do not need to include this line for this tutorial, but remember it for the future.

Creating your first page

We need to create a few files to get us started. The first is the main index of the page; call this file index.php and place it in the root directory. Add the following code to your new file:

				<?php
require $_SERVER['DOCUMENT_ROOT'] . '/theme/overallheader.php';
include $_SERVER['DOCUMENT_ROOT'] . '/theme/header.php';
include 'content.php';
include $_SERVER['DOCUMENT_ROOT'] . '/theme/footer.php';
require $_SERVER['DOCUMENT_ROOT'] . '/theme/overallfooter.php';
?>

This is your basic set of PHP includes, and will be required on every index page. The first line loads the file named overallheader.php into the index page, followed by header.php, content.php etc... The first and last two lines are dynamically loaded from the theme directory, so if you change one of those files, that change will be reflected across the entire site. The content.php file is the contents of the page you are looking at, and so it is included using its relative path, which will always be the directory of the index.php file, and therefore never needs to change.

So now we need to create those five files and see if it works. Copy the contents from the code below, and create the files within the theme directory. Or alternatively download the completed template here. Be sure to keep the line-breaks as shown below, this ensures the page source structure remains neet & tidy.

overallheader.php

				<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="/style.css" rel="stylesheet" />
</head>
<body>

header.php

				<!-- Header -->
<header>
header / navigation menu
</header>
<!-- End Header -->

footer.php

				<!-- Footer -->
<footer>
<div id="leftfoot">
<p>Web Design Template by Daniel Keith Jones</p>
</div>
<div id="rightfoot">
<p>(cc) <?php echo date("Y") ?> - www.danielkeithjones.com</p>
</div>
</footer>
<!-- End Footer -->

overallfooter.php

				</body>
</html>



Now create the page contents. Place this in the root directory of your site (htdocs).

content.php

				<!-- Content -->
<div id="content">
<p>Your Homepage</p>
</div>
<!-- End Content -->



Lastly, to get our new page to look good, lets create the stylesheet. Copy the code below and save it in the root directory as style.css.

				@charset "utf-8";

* {
margin:0;
padding:0;
border:none;
font-size:12px;
font-family:Arial, Helvetica, Verdana, sans-serif;
font-weight:normal;
color:#000;
outline:none;
}

body, html {
width:100%;
height:100%;
}

body {
background:#bbb;
text-align:center;
width:900px;
margin:10px auto;
}

header {
height:50px;
margin:10px auto;
background:#333;
color:#fff;
box-shadow:0px 5px 10px -2px #666;
}

#content {
min-height:700px;
margin:0 auto 10px auto;
background:#fff;
box-shadow:0px 5px 15px -5px #666;
}

header, #content {
width:900px;
border-radius:10px;
}

footer {
width:900px;
height:50px;
margin:10px auto;
color:#333;
}

#leftfoot {
float:left;
position:relative;
left:5px;
}

#rightfoot {
float:right;
position:relative;
right:5px;
}

Once you have your files created, go ahead and test your new page by navigating to http://localhost/

Your site should look something like this:


You can change the layout to your liking by modifying the stylesheet yourself. For now we're only interested in the PHP.

PHP include vs. require

You may have noticed in the section above, the use of both include and require for the index.php file we created. PHP provides four functions that enable you to insert code from other files:

  • include()
  • require()
  • include_once()
  • require_once()


All four can be used to insert code from a local source file, but not from a remote file or external site. require() & include() are virtually the same, except for the way they handle an irretrievable resource. include() & include_once() will give-out a warning if a resource cannot be retrieved, and try to continue execution of the script if possible. require() & require_once() will stop processing and give-out a "Fatal Error". In most cases we would want the script to continue if there was an error, so we would use include(). For layout critical resources such as the overallheader.php, we would use require(), as an error with this resource would give-out too many errors on the page, causing it to load incorrectly; or not at all.

include_once() & require_once() ensure that the resource is only processed once on the page. This is useful in situations where multiple files may reference the same resource, since a function cannot be defined twice.

What about page specific headers & footers?

So you have your basic file structure set-up, but what if you want just one page to have unique JavaScript, or additional headers that aren't needed on any other page? We turn to our includes again. Assuming your page layout is the same in your chosen sub-directory, it's just a matter of calling-in some additional files. We should make this dynamic in-keeping with the rest of the site, so let's include this in the overallheader section that we created earlier.

Open the overallheader.php file from the theme directory, and modify the code to match the following:

				<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="/style.css" rel="stylesheet" />
<?php if(file_exists('headers.php')) { echo "t"; include 'headers.php'; echo "n"; } ?>
</head>
<body>

The PHP include that we just added to overallheader.php will only be called if the file exists in the relative directory. So now we just need to create a new file with the additional headers desired, for example:

				<script src="/js/functions.js"></script>

This tag will then be added along with the rest of the headers for that specific page only. This same method can be used to include additional footers / JavaScript too.

The code below works the same way as above, but adding the <script> & </script> tags before & after the included source file. You can then add any JavaScript or JQuery functions to a file named scripts.php, and place it in the relative directory. This makes it easier to keep your site dynamic, even if you don't need any JavaScript yet, chances are you will eventually.

				<?php if(file_exists('scripts.php')) {
echo "t" . '<script>' . "nt" . '/* <![CDATA[ */';
include 'scripts.php';
echo "t" . '/* ]]> */' . "nt" . '</script>' . "n"; };
?>

Be sure to place this after your headers.php include function.

What about meta data?

The meta data for any page is set in the head section, so we should set-up a default string to use for the page title and description. This can be done by changing overallheader.php once again:

				<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?php if(isset($title)) { echo $title; }
else { echo 'This is the default page tite'; } ?></title>
<meta name="description" content="
<?php if(isset($description)) { echo $description; }
else { echo 'This is the default page description.'; } ?>" />
<link href="/style.css" rel="stylesheet" />
</head>
<body>

Now you can specify your page title and description using strings in the index.php file, for example:

				<?php
$title = 'Articles'; // Page title
require $_SERVER['DOCUMENT_ROOT'] . '/theme/overallheader.php';
include $_SERVER['DOCUMENT_ROOT'] . '/theme/header.php';
include 'content.php';
include $_SERVER['DOCUMENT_ROOT'] . '/theme/footer.php';
require $_SERVER['DOCUMENT_ROOT'] . '/theme/overallfooter.php';
?>

Here, the description string has not been set, so the page will display the default values instead.

Article Updated: Mon 20th Apr 2015