1

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

I am getting warnings. I would like to take care of it. Here is the offending code

if ($_REQUEST['login']) $user = $_REQUEST['login'];
elseif ($_COOKIE['user']) $user = $_COOKIE['user'];

if ($_REQUEST['encpas']) $pass = $_REQUEST['encpas'];
elseif ($_COOKIE['pass']) $pass = $_COOKIE['pass'];

if ($_REQUEST['randsess']) $sess = $_REQUEST['randsess'];
elseif ($_COOKIE['sess']) $sess= $_COOKIE['sess'];

I am not sure how to get rid of them.

Thanks

Community
  • 1
  • 1
Cocoa Dev
  • 9,361
  • 31
  • 109
  • 177
  • 4
    `$_REQUEST['login']` isn't defined; the notice even gives you the line number – Don Aug 10 '12 at 19:38
  • 1
    Always make sure the index exists before trying to do stuff with it. – Matt Aug 10 '12 at 19:39
  • Also since it seems you are relatively new to PHP development, I would highly recommend you not use $_REQUEST superglobal unless you really have cases where you might get a parameter passed via POST or GET. I would imagine you are trying to process a POSTed login, so you should probably use $_POST as you probably don't want people to be able to append login credentials to your URL and have them work. – Mike Brant Aug 10 '12 at 19:45
  • I am brand spanking new to PHP. Thanks. I am trying to work with an abandoned OpenSource PHP project. So the first task is to get it 2 work. Then update and modernize the code to today's specs – Cocoa Dev Aug 10 '12 at 19:51

3 Answers3

6

Check your variables to see if they set and have a value or not:

if ( isset($_REQUEST['login']) ) { 
    $user = $_REQUEST['login'];
} elseif ( isset($_COOKIE['user']) ) {
    $user = $_COOKIE['user'];
}
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
0

Try using isset() to check if the index has been initialized before you check if it's true or not. http://au.php.net/manual/en/function.isset.php

Abraham Brookes
  • 1,720
  • 1
  • 17
  • 32
0

You should use array_key_exists, or isset. The last is faster according to some benchmarks.

if( isset( $_REQUEST['login'] ) ) {
  $user = $_REQUEST['login'];
}

isset doesn't count NULL as value.

Be careful with this because the following:

index.php?login=&otherstuff

Will set login with empty value. But it will be set.

JorgeeFG
  • 5,651
  • 12
  • 59
  • 92