Using a cookie as a variable in a Switch statement in PHP

348 Views Asked by At

This snippet of code is suppose to compare the value of the $_COOKIE variable and move forward accordingly but instead I am getting the error

Undefined index = type

Here is the code -

if ($result != false) {
$session_data = array(
'username' => $result[0]->username, //THIS WAS PREVIOUSLY user_name
'password' => $result[0]->password,
'type' => $result[0]->type,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);


if (in_array($_COOKIE['type'], array("Admin", "User", "Library")))
switch ($_COOKIE['type']) {
case "Admin":
$this->load->view('admin_page');
break;

case "User":
$this->load->view('viewtry');
break;

case "Library":
    echo "yes";
    break;
default:
    echo "no";
}

****UPDATE****

I solved my problem, what I did was just replaced the two instances of $_COOKIE['type'] with simply the variable $type as I declared it earlier. Kinda stupid of me to overlook that.

Thanks for the solutions.

2

There are 2 best solutions below

1
On BEST ANSWER

$COOKIE doesn't have type key. So, before get value of the type, you should check that the type was defined or not. You can use the function that is called isset for checking key.

if ($result != false) {
$session_data = array(
'username' => $result[0]->username, //THIS WAS PREVIOUSLY user_name
'password' => $result[0]->password,
'type' => $result[0]->type,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);


if (isset($_COOKIE['type']) && in_array($_COOKIE['type'], array("Admin", "User", "Library")))
switch ($_COOKIE['type']) {
case "Admin":
$this->load->view('admin_page');
break;

case "User":
$this->load->view('viewtry');
break;

case "Library":
    echo "yes";
    break;
default:
    echo "no";
}
0
On

You should avoid having your switch logic inside an if block. Instead consider something like:

$user_type = 
    (in_array($_COOKIE['type'], array("Admin", "User", "Library"))) 
    ? $_COOKIE['type'] 
    : NULL;

switch ($user_type) {
    case "Admin":
        $this->load->view('admin_page');
    break;

    case "User":
        $this->load->view('viewtry');
    break;

    case "Library":
        echo "yes";
    break;

    default:
        echo "no";
}

This way, $user_type gets set to NULL if $_COOKIE['type'] isn't passed into the request, so it will be handled as the default in your switch.