PHP: Navigation by Variables
Tutorials > PHP > Navigation by Variables
PHP: Navigation by Variables
Related Link: PHP: Calling External Scripts (Include and Require)
This tutorial simply shows you how you can create a php navigation system for your site. Why would you want to do this? Well, let me tell you:
- You can manage all of your links in your main index page.
- Easy to manage content and styles/layouts.
There are also good reasons not to use this, which virtually no one will ever tell you:
- It can be hard to keep track of your content, especially in larger sites.
- There are no 'hard' URLs since all your content is generated from a variable.
- To develop any sort of script that sends headers can be a pain because all headers must be sent before any output.
Generally speaking, this method can be quite useful. It makes it easy to manage navigation and styles. On the other hand, though, if your site starts to include a fair amount of content and scripts, you can be sure to run into some problems unless you have your pages written individually, which then defeats the purpose of this navigation script.
For example: I use index.php to manage my links. Fair enough. I have each page of my site linked into index.php which is called when variable 'x' is parsed (taken) from the browser query string. Index.php also holds my page template, and my content is output in the middle of the template, where I want my content to be. Now, if I decide I want to set a cookie, the setcookie header has to be sent out before anything else, therefore, including it within the already partially output template will not work. I have to resort to including my templates as and when I need them within each page of content. This then renders the use of navigation by variables pointless. I might as well use 'hard' URLs which are easier to track and take PHP right out of all navigation!
If you only want to include textual content and parse simple php scripts, this method will work for you. If you're more of a hardcore programmer (like me) then I recommend developing a style system that is easy to implement and coding hard URLs into your HTML navigation (i.e. "/folder/file.php").
The Code (at last!):
OK, now we've got that out of the way, and you've decided you still want to know how to implement this method, I'll show you. It's very simple:
<?php
// $x is the variable taken from the browser
// Newer PHP versions don't require you to use $_GET
if( $_GET['x'] ){
$x = $_GET['x'];
}
switch( $x ) {
case "var1":
include("page1.php");
break;
case "var2":
include("page2.php");
break;
default: // for when x is not set
include("defaultpage.php");
break;
}
?>
And that's it for the PHP side! Now all you have to do is write your URL references in a similar way to the following:
<a href="index.php">Home</a>
<a href="index.php?x=var1">Page 1</a>
<a href="index.php?x=var2">Page 2</a>