tags:

views:

10

answers:

3

Hey guys,

I’m working on a site and I kept getting a

Notice: Undefined index: id in file root on line 3

I know its something simple but can’t figure out where the problem lies exactly.

here is the code:

<?php
    switch($_GET['id']) {
        default:
            include('pages/hello.php');
        break;
        case "testimonials": 
            include('pages/testimonials.php');
        break;
        case "faq":
            include('pages/faq.php');
        break;
        case "raq":
            include('pages/raq.php');
        break;
        case "contact":
            include('pages/contact.php');
        break;
    }
?>

line 3 would be <?php switch($_GET['id']) {

any help would be greatly appreciated!

A: 

It seems that the url parameter 'id' is not defined, that's the cause of the notice.

You should first check for its existence, eg.

if (isset($_GET['id'])) {
  your code here
}
Vasileios Lourdas
A: 

Make sure that id is set and the default should go at the end:

if (!isset($_GET['id'])) {
  include('pages/hello.php');
}
else{
  switch($_GET['id']) {
    case "testimonials": include('pages/testimonials.php'); break;
    case "faq": include('pages/faq.php'); break;
    case "raq": include('pages/raq.php'); break;
    case "contact": include('pages/contact.php'); break;
    default: include('pages/hello.php'); break;
  }
}

For security reasons, make sure to sanitalize yor $_GET['id']. I would suggest you to setup an array of allowed pages and include those that are in the array. You can use in_array function for that.

Sarfraz
A: 

This is because in your url id=x is not always set, so when your trying to switc hthe value its not there. what you should do is like so:

<?php

    $id = isset($_GET['id']) ? $_GET['id'] : ''; //This is just  a short if-else
    switch($id)
    {
        default:
            include('pages/hello.php');
        break;
        case "testimonials": 
            include('pages/testimonials.php');
        break;
        case "faq":
            include('pages/faq.php');
        break;
        case "raq":
            include('pages/raq.php');
        break;
        case "contact":
            include('pages/contact.php');
        break;
    }
?>

Basciall $id = isset($_GET['id']) ? $_GET['id'] : ''; what this says is, IF id is within the url then use that, otherwise use an empty string, the reason for the empty string is it will trigger the default: within the switch statement

this way $id will always be set to something.

RobertPitt
This worked perfectly. Thanks man!
Chaddoesdesign
If this is the answer that helped you the most and you feel though its the most correct answer for your question please use the Tick to the right of this post to mark it as your selected answer, And your welcome.
RobertPitt