views:

26

answers:

2

I my login form if I dont check remember me check box in php script it gives <b>Notice</b>: Undefined index: autologin in error. in my .php file I have $check_autologin = $_POST['autologin']; And I am checking is user checked it

if($check_autologin == 1)
    {
   $password_hash = $encrypted_mypassword;     
   setcookie ($cookie_name, 'usr='.$username.'&hash='.$password_hash, time() + $cookie_time);
   }

and this is my check box field <input type="checkbox" name="autologin" value="1">Remember Me<br />

How could check box can return any default value if it is not checked?

+2  A: 

I suspect the problem is when your checkbox is not checked the value doesn't exist in the $_POST array.

Try insulating your value check by using

isset( $_POST['autologin'] )

thusly:

$check_autologin = false;
if( isset( $_POST['autologin'] ) ) {
    $check_autologin = $_POST['autologin'];
}
cori
+1 for `isset()`. When PHP is in strict mode, it produces a notice if you have not checked for existance before using an index. `empty()` is a useful alternative.
elusive
A: 

Undefined Index means that you're asking PHP to tell you the value of an array element that doesn't exist.

It is a 'Notice', which means it isn't a fatal error and doesn't stop the program from running, but is a good idea to fix. (it is also possible to set PHP so it doesn't report Notice-level events, but again, better just to fix the problem)

How to fix it?

a) As already suggested, check whether it's been set before you check what the value is. So rather than just saying if($_POST['x']) say if(isset($_POST['x]) && $_POST['x'])

b) Explicitly supress the warning. PHP allows you to do this with the @ symbol. So you would say if(@$_POST['x'])

c) Ensure that you only ever make reference to variables that you know have been set. This would mean a different approach to your code, but could be a start toward making it more robust in general. For example, rather than looking directly at the $_POST values you're expecting, you could write a foreach($_POST) loop which allows you to inspect everything in $_POST. This would also allow you to spot when someone posts values you're not expecting to receive.

Spudley