mikwaheeri
mikwaheeri

Reputation: 3

Using If/Else for PHP menu navigation

I'm looking for some feedback on using If/Else for my menu navigation or links to resources. I have done a few quick searches and have found items relating to using PHP to keep track of the current page and apply specific CSS rather than implementing the menu itself.

What I'm trying to do is have the menu change my content div based on the menu. So if "home" is clicked, the div changes to home and if "about" is clicked, the div changes to about.

What I've done so far is to create a variable 'cl' that I set using the id attribute in each div. In my index page I use the following:

//if cl is not set include default content div
if(!isset($_GET['cl']))
{
     //include main div
}

//if cl is set, check value and include the correct div
//anything that does not match a hard-coded cl value --SHOULD-- default to main
//div...may change this to be a custom error page
if(isset($_GET['cl']))
{
    if($_GET['cl']=="content-main")
    {
        //include main content div
    }
    elseif($_GET['cl']=="content-anotherPage")
    {
        //include another page div
    }
    else
    {
        //include main content or possibly custom error
    }
}

I have more elseif blocks thrown in for other menu items, but left this small to just show what I'm doing.

Is this method a valid approach? Are there any basic things I'm missing that I should be aware of? Is my If/else block secured? (By secure I mean changing the value of URL should just revert to the default content div. I tried placing a basic javascript alert script into the URL and it did default to the main page, but not sure if my basic test relates to actual security).

First time poster...please let me know if I have not followed etiquette and I will gladly correct!

Mike

Upvotes: 0

Views: 1339

Answers (2)

Revent
Revent

Reputation: 2109

If you have lots of conditions, I would use a switch statement instead http://www.w3schools.com/php/php_switch.asp as it's much faster. If you only have a few conditions like less than 5 or 6, if/else is fine.

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

instead of bunch of if/elseif's I'd rather use switch/case syntax:

switch( $_GET['cl'] ) {
    case "content-main":
       ...
       break;

    default:
       ...
       break;
}

Upvotes: 2

Related Questions