简体   繁体   中英

Why does empty() throw an 'Undefined Index'-Error?

My code is as follows. In my understanding from diverse websites and the php documentation, empty() is a language construct that checks whether the key exists, just like isset() (only that it also does a loose 'false'-comparison in case the Variable or Key exists...

37     $origin = 
38                !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :
39                !empty($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] :
40                !empty($_SERVER['ORIGIN']) ? $_SERVER['ORIGIN'] :
41                "Unknown Origin";

Error:

Undefined index: ORIGIN in somePHPFile.php:40

Update: I fixed it by wrapping the else-parts in parentheses. When i have discovered the exact problem (associativity or else...) i will update this answer again.

        $origin = 
            (!empty($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] :
            ((!empty($_SERVER['HTTP_ORIGIN'])) ? $_SERVER['HTTP_ORIGIN'] :
            (!empty($_SERVER['ORIGIN']) ? $_SERVER['ORIGIN'] :
            "Unbekannte Herkunft"));

The reason for this error is associativity of ternary operator in PHP - it's left-to-right , while in most other languages it's right-to-left. That's why nested ternaries are very cumbersome both to read and to write in PHP. )

In this particular case it means, in particular, the following: if HTTP_REFERER header is set, the value of $_SERVER['HTTP_ORIGIN'] will be checked as well.

To solve this, you need to either wrap the conditions in parenthesis, use plain old if-elseif-else combination, or (makes most sense to me) do some abstraction over your code:

$origin = 'Unknown Origin';
$headersToCheck = ['HTTP_REFERER', 'HTTP_ORIGIN', 'ORIGIN'];
foreach ($headersToCheck as $header) {
  if (!empty($_SERVER[$header]) {
    $origin = $_SERVER[$header];
    break;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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