Geronimo89.dk

A blog about me, my doings and everything I think deserves attention.

First website and navigation with PHP

This little tutorial will teach you how to build a website with multiple pages with PHP. When I started trying to make websites, I used frames/iframes which are BAD and not valid html code. So we now we want to use the PHP function include(), which gives us the ability to display other documents inside another.

So let’s start out with a standard xhtml document called index.php:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Navigation with PHP</title>
</head>
<body>
</body>
</html>

Before the doctype we now insert a list of our files. Let’s say we have files called “news.php” “home.php” and “about.php”.

<?php
$section = array();
$section[‘home’] = “home.php”;
$section[‘news’] = “news.php”;
$section[‘about’] = “about.php”;?>

Now this “list” actually puts all these as entries into an array in PHP. We’ll need that later. Now we head down to the <body> tag and insert some php code here. What we’ve done until now is only creating a list with the files we may want to show inside our website. So if we want to display our content, we should add the next part where you want the content to appear.

<div id=”content”><?php
if (isset($_GET[‘section’], $section[$_GET[‘section’]])) {
include $section[$_GET[‘section’]];
} else {
include $section[‘home’];
}?>
</div>

Now our website has the ability to include the listed files and make them appear as a part of the site. I’ve already created a <div> around it, you don’t have to do that. The last thing to do is to add the navigation with the links that tells the PHP script which file to load. If there are no or no valid options given, it does include $section[‘home’];. This first of all makes the script include home.php when only index.php is opened and makes the site safer, because no not listed files can be included like /etc/passwd. icon wink First website and navigation with PHP

<ul>
<li><a href=”index.php?section=home”>Home</a></li>
<li><a href=”index.php?section=news”>News</a></li>
<li><a href=”index.php?section=about”>About</a></li>
</ul>

I’ve already put the links in a list, you don’t have to do that, but it looks nicer. The part between the <a> and </a> is the essential one. Through opening index.php?section=news you tell the index.php to include the file saved with the array entry news.

That’s basically it. You’ve learned how to avoid frames and create a website with multiple pages!

Give me the first comment

Leave a Reply