Stumped - PHP

Status
Not open for further replies.

Mike

New member
Jun 27, 2006
6,777
116
0
51
On the firing line
I would like my page to respond to a query string in my URL. If there is nothing, I would like it to default to something. Make sense?

Anyhow, here is the code I am using:
Code:
<?php $id = $_GET['id'];
if (isset ($id))
    {
    $var = $id;
    }
else
    {
    $var = "Something here";
    }
 ?>
And the error that I keep getting:

Notice: Undefined index: id in /home/xxxxxxxxxx/public_html/index.php on line 3
I understand that it's saying "Hey stupid, you have a variable but no value for it"

How do I correct this?

But it does set $var to whatever and that will show up on the page in the spots where I have echo $var. So, it's sort of working.
 


You need to try putting using isset before you attempt to assign $id to whatever is in your GET array.

Think along these lines: if(isset($_GET['id'])) { $id = $_GET['id'] }

EDIT: you've got REGISTER_GLOBALS turned on, which is why it sort of works as-is. When you use $id on the second line, it's assuming you mean $_GET['id'] and using the value from there. For all sorts of reasons this is extremely bad news.
 
Code:
elseif($var==null)
{
$var = "default";
}

Maybe something like that?
 
I need to read into things further. They are correct on your use of isset.
 
EDIT: you've got REGISTER_GLOBALS turned on, which is why it sort of works as-is. When you use $id on the second line, it's assuming you mean $_GET['id'] and using the value from there. For all sorts of reasons this is extremely bad news.

Just wanted to hammer home this point. REGISTER_GLOBALS poses a major security risk and is best left off.
 
My version might look like:
Code:
<?php
$id = isset($_GET['id']) ? $_GET['id] : "whatever";
$id = is_numeric($id) ? intval($id) : "whatever else";
?>
 
Thanks everyone! My server has PHP 4.7 and register_globals is turned off. I double checked using phpinfo()

Anyhow, this is the code that ultimately worked:
Code:
<?php
if(isset($_GET['id']))
    {
    $id = $_GET['id'];
    }
else
    {
    $id = "Default statement";
    }
 ?>
 
This is the best solution in my opinion:

Code:
$var = (isset($_GET['id'])) ? $_GET['id'] ; 'Something here';
 
I prefer this style, easier to read compared to having it on one line.
Code:
<?php
if(isset($_GET['id']))
    {
    $id = $_GET['id'];
    }
else
    {
    $id = "Default statement";
    }
 ?>
 
Status
Not open for further replies.