Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined index: Error in php script

Tags:

php

request

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?

like image 829
Yogi Yang 007 Avatar asked Jan 29 '10 06:01

Yogi Yang 007


2 Answers

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.

like image 87
zombat Avatar answered Oct 07 '22 16:10

zombat


Another solution is to use the following:

$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : '';

You can also, if you prefer to return a value other than empty, by placing a default value within the final set of single quotes, e.g.

$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : 'Default Value';

or return a different variable type, for instance an integer:

$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : 34;
like image 44
Bryan Avatar answered Oct 07 '22 14:10

Bryan