0

I am making a website and am getting thrown this error when I go to www.mydomain.org. This code Works when going to http://mydomain.org/index.php?id=home

How do I fix this as I don't want people to have to type in the /index.php?id=home

<div id="middle_main">
    <?php   
          $page = $_GET['id']; 
          if ($page == "") { include "pages/home.html"; } 
          else { include "pages/$page.html"; } 

    ?>
</div>
  • 2
    This will help you http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12770836#12770836 – asprin Mar 06 '14 at 16:25

2 Answers2

0

Check if it is set, if not, set it to 'home':

$page = isset($_GET['id']) ? $_GET['id'] : 'home';

Then you don't need an if statement to check it is set:

include "pages/$page.html";
George
  • 36,413
  • 9
  • 66
  • 103
  • Ah much thanks. I actually do still need the if statement. It throws a syntax error if it is removed, but it works with your added line how I want it to. – user3389088 Mar 06 '14 at 16:30
  • You shouldn't need an if statement anymore to check that the variable has value. You will need to check whether the value is a 'valid section' of your site though. – George Mar 06 '14 at 16:32
0

Notices are really recent in PHP development, and they are not errors, which means you don't have to fix them. Yet, this is a very good practise to do so.

The undefined index notice warns you that you are trying to read an array index that hasn't been initialised. In your case, you try to read the home index of the $_GET array. When your URL is something.php?home=something, then $_GET['home'] is initialised automatically, and no notice appears. However, when you access something.php, this index isn't set, which explains the notice !

In your code, you need to check whether this index is set, and assign it a default value when it isn't.

$page = isset($_GET['home']) ? $_GET['home'] : 'home';

In this case, if the home index isn't set, $page will be set to "home". See http://davidwalsh.name/php-shorthand-if-else-ternary-operators if you want to know more about the ternary operator (? and :) which I've just used.

John WH Smith
  • 2,743
  • 1
  • 21
  • 31