on Sat Jul 05 08:32:13 GMT 2008 in PHP and viewed 4845 times
How to build another PHP navigation using the switch() statements. Includes an explanation of GET variables.
This style of navigation is much more implementable than the classic include(”$id.php”) style of PHP navigation. This entails using the very useful function of PHP, switch.
GET variables are variables defined in the URI, defined after a question mark, and seperated by an ampersand (&). Enough explaining, let’s jump in here, shall we?
<?php
$page = $_GET["page"];
$id = htmlentities(trim($page), ENT_QUOTES);
switch($id){
default:
?>
This page will show if:<br />
1. The id value is blank or<br />
2. The id value is not covered in the cases.
<?
break;
case "1":
echo "This is page 1.";
break;
}
?>
The basics of this is that id has the value of the GET variable “page.” As explained earlier, a GET variable is a variable defined in the URI after a question mark (?). You can access these variables by using $_GET[]. It acts as an array, so if the URI is defined as http://mysite/page.php?some=foo, then it can be accessed by using $_GET["some"].
Back to the page, after I read the GET variable into $page, I then sanitized page by defining $id as the sanitized $page. We need to escape characters dangerous to the application. What if that GET variable was to be used in an SQL query? Someone could easily hack into your application. Or a javascript redirect placed into a comment for a blogging application that redirects anyone who views that post to be redirected to the “hacker’s” own site. The two functions I used was htmlentities() and trim. You use htmlentities() escape all of the different things that could hurt an application, like <, >, double-quotes (””), single-quotes (’’), and ampersands (&). Also remember that htmlentities won’t escape double-quotes without defining the second argument as “ENT_QUTOES.” To escape a string properly, it would be htmlentities($string, ENT_QUOTES).
The second function, trim(), just clears whitespace from the beginning or end of a string. So ” Hello ” becomes “Hello”.
The rest of the code is some easy PHP. Just a switch statement that relies on the $id variable. If no variable is defined, it defaults to the default case. Otherwise, it’ll go to the proper case. If $id = 3, the application will display case “3”, and etc.
Schwing. Nice one dude
by simon