简体   繁体   English

在PHP的Switch语句中使用cookie作为变量

[英]Using a cookie as a variable in a Switch statement in PHP

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 此代码段假定是比较$_COOKIE变量的值并相应地向前移动,但是相反,我遇到了错误

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. 我解决了我的问题,我所做的只是将$_COOKIE['type']的两个实例替换为我先前声明的变量$type Kinda stupid of me to overlook that. 我有点愚蠢地忽视了这一点。

Thanks for the solutions. 感谢您的解决方案。

$COOKIE doesn't have type key. $COOKIE没有type密钥。 So, before get value of the type , you should check that the type was defined or not. 因此,在获取type值之前,应检查type已定义。 You can use the function that is called isset for checking key. 您可以使用称为isset的函数来检查密钥。

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";
}

You should avoid having your switch logic inside an if block. 您应该避免将switch逻辑包含在if块中。 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 . 这样,如果未将$_COOKIE['type']传递到请求中,则$user_type会被设置为NULL ,因此它将作为switchdefault处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM