tags:

views:

195

answers:

4

In a php page I have following code:

if($_REQUEST['c']!="") // I get error on this line itself. Why?
{
 $pidis=(int)($_REQUEST['c']);
}

I keep getting Undefined index error.

On Googling I manage to understand that if a page is access without parameters (in URL) which we are trying to access we can get this error/warning. I believe that if a parameter is not defined in the URL it should just return empty instead of giving error/warning message.

I know that it is possible to suppress errors and warning by adding

error_reporting(E_ALL ^ E_NOTICE);

But I do not want to do this.

This same page work just fine on our company's web server but does not work on our clients web server.

Why is this happening?

How to solve this problem?

A: 

Use isset($_REQUEST['c']) to test if it exists first.

Ignacio Vazquez-Abrams
+5  A: 

You are getting that error because you are attempting to compare $_REQUEST['c'] to something when $_REQUEST['c'] does not exist.

The solution is to use isset() before comparing it. This will remove the warning, since the comparison won't happen if $_REQUEST['c'] doesn't exist.

if(isset($_REQUEST['c']) && $_REQUEST['c']!="")
{
 $pidis=(int)($_REQUEST['c']);
}

It is an E_NOTICE level error, and your level of error reporting will affect whether the error shows up or not. Your client's server has E_NOTICE level error reporting turned on, which is why it shows up there.

It is a good idea to always develop using E_ALL so that you can catch this kind of error before moving your code to other servers.

zombat
A: 

PHP is giving a notice (which is not an error : it's just a notice) when you are trying to use a variable that doesn't exists, or an array element that doesn't exist.

This is just to help you, and you should not mask those notices : they are here to help you -- for instance, to help you detect typos in variable names.

Before using that array index, if it's not always present, you should test if it's here, using isset :

if (isset($_REQUEST['c']) && $_REQUEST['c']!="") {
    // ...
}
Pascal MARTIN
+1  A: 

Instead of isset() you can also use: array_key_exists().

The difference between both methods is that isset() checks also whether the value of the variable is null. If it is null then isset returns false whereas array_key_exists() returns always true if the key exists (no mater which value). E.g.:

$array = array('c' => null);

var_dump(isset($array['c']))); // isset() returns FALSE here
var_dump(array_key_exists($array['c']); //array_key_exists() returns TRUE

Depending on the context, it is important to distinguish this. In your case I don't think it matters doesn't matter, as (I guess) a request parameter never will be null (except one overwrites it manually).

Felix Kling