I am getting this “Notice: Undefined index: id” error message for my login system. I have tried several things to fix this but i have had no luck, i have used the most obvious solution, the isset function but i have had no luck. Please help.
This is the error message… Notice: Undefined index: id in /Applications/MAMP/htdocs/project/functions.php on line 4. The code for the functions page is below, if i need to include other pages please let me know.
Thanks in advance
<?php
function is_logged_in(){
if($_SESSION['id'] or $_COOKIE['id']){
if($_COOKIE['id'] and !$_SESSION['id']) $_SESSION['id'] = $_COOKIE['id'];
return $_SESSION['id'];
}
else
return false;
}
function redirect_if_logged_in(){
if(is_logged_in()){
echo 'You are logged in. Redirecting!!';
redirect2home();
}
}
function redirect_if_not_logged_in(){
if(!is_logged_in()){
echo 'You are not logged in. Redirecting!!';
redirect2home();
}
}
function redirect2home(){
die('<META HTTP-EQUIV="refresh" CONTENT="5; URL=personal.php">');
}
?>
Assuming the above is line 4, either the $_SESSION or $_COOKIE arrays are missing an ‘id’ index. Have you var_dumped the arrays to see which one is missing?
var_dump($_SESSION, $_COOKIE); die;
And, if you actually don’t expect that part of the array to have a value at any time, then you should use isset to avoid the errors. Here is a good article on that.
function is_logged_in(){
if(isset($_SESSION['id']) or isset($_COOKIE['id'])){
One other thing I am a little worried about. You pass either the session id back or false. Although PHP allows that (I think?), I don’t believe that is good programming. The function should return one type of value back. Either a boolean or a value for $_SESSION[‘id’], whereas, since $_SESSION is a global variable anyway, there is no need to pass it. It is global. And since your function name infers a boolean result, I think you should actually return “true” or “false” back from the function and make sure your calling code works properly with that boolean value.
Another rule of thumb in programming is to always return out of a function, if things aren’t right for it first. For a short method like this, maybe not so important, but for methods with a lot of “work” being done, it helps your application perform better. Generally though, you should follow the rule as a best practice.
So, with all of that said, I propose this new function…
function is_logged_in(){
// make sure at least one variable is available, if not. Leave the function, because the user isn't logged in.
if( !isset($_SESSION['id']) and !isset($_COOKIE['id'] )){
return false;
}
// use isset here to avoid the notice errors
if( isset($_COOKIE['id']) and !isset($_SESSION['id'] )) {
$_SESSION['id'] = $_COOKIE['id'];
return true;
}
// if all else fails, take the safer side
return false;
}