Jump to content

Undefined variable error


guidance51x

Recommended Posts

Hey Everyone. I've been using a piece of code several times before and its worked fine but now (after updating my php version) I get an error.

Heres the code:

 

if(isset($_GET['id']) == TRUE){	
if(is_numeric($_GET['id'])==FALSE) {
	$error = 1;
}
if($error == 1){
	header("Location: " . $config_basedir);
}
else{
	$validentry = $_GET['id'];
}
}
else{
$validentry = 1;
}

 

The line with "if($error == 1){" gets flagged with an error saying:

Notice: Undefined variable: error in C:\xampp\htdocs\sites\smd\index.php on line 8

 

I've used the code before with no problems and uploaded to my web server I also have no errors. What did I do wrong. I hope it isn't a seriously stupid error.

 

Thanks in advance.

Link to comment
Share on other sites

Like the message says, it's a notice. That's the lowest level of "error" message that PHP will generate.

 

The problem is that if that second condition (with is_numeric()) isn't true, $error will not be set to 1. Which means PHP doesn't know what $error is supposed to be when you try to test it ==1. For all PHP knows, there's a bug in the code and you forgot to set $error=0 beforehand. Or worse: you forgot to set $error=1 beforehand. PHP will then pretend that $error=null and continue with your code.

 

The solution is simple: set $error=0 somewhere earlier. Like before that second condition. Thus it will always have a value.

Link to comment
Share on other sites

There's a few ways around this.

 

option 1:

if(isset($_GET['id']) == TRUE){	
if(is_numeric($_GET['id'])==FALSE) {
	$error = 1;
}else{
                $error = 0;
        }
if($error == 1){
	header("Location: " . $config_basedir);
}
else{
	$validentry = $_GET['id'];
}
}
else{
$validentry = 1;
}

 

option 2:

$error = 0;
if(isset($_GET['id']) == TRUE){	
if(is_numeric($_GET['id'])==FALSE) {
	$error = 1;
}
if($error == 1){
	header("Location: " . $config_basedir);
}
else{
	$validentry = $_GET['id'];
}
}
else{
$validentry = 1;
}

 

option 3:

 

if(isset($_GET['id']) == TRUE){	
if(is_numeric($_GET['id'])==FALSE) {
	$error = 1;
}
if(@$error == 1){ //the @ will hide errors for that var, it also works on functions
	header("Location: " . $config_basedir);
}
else{
	$validentry = $_GET['id'];
}
}
else{
$validentry = 1;
}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.