How would I test if a cookie is set using php and if it's not set do nothing

前端 未结 5 1501
再見小時候
再見小時候 2021-02-07 04:06

I\'ve tried

 $cookie = $_COOKIE[\'cookie\'];

if the cookie is not set it will give me an error

PHP ERROR
Undefined index: cook         


        
5条回答
  •  囚心锁ツ
    2021-02-07 04:18

    Depending on your needs.

    // If not set, $cookie = NULL;
    if (isset($_COOKIE['cookie'])) { $cookie = $_COOKIE['cookie']; }
    

    or

    // If not set, $cookie = '';
    $cookie = (isset($_COOKIE['cookie'])) ? $_COOKIE['cookie'] : '';
    

    or

    // If not set, $cookie = false;
    $cookie = (isset($_COOKIE['cookie'])) ? $_COOKIE['cookie'] : false;
    

    References:

    • isset()
    • ternary operator (?)

提交回复
热议问题