Trying to access array offset on value in PHP 7.4

I just upgraded my server's PHP version to PHP 7.4.1 and now getting this error: Notice: Trying to access array offset on value of type bool in

if ($info['msg'] == CURLMSG_DONE) {
    $channel = $info['handle'];
    $page = array_search($channel, $this->pages);
    $this->pages[$page] = curl_multi_getcontent($channel);
    $this->multiHandlingRemove($channel);
    curl_close($channel);
}

What is the fix for PHP 7.4 ?

Upvotes: 0

Views: 597

Answers (1)

zanderwar
zanderwar

Reputation: 3730

The reason for your error is because array_search will return false when nothing was found, and a boolean cannot be used as an array offset (also known as an array index).

This indicates that your script has been producing likely undesirable results in certain scenarios for sometime now, you need to check that false was not returned:

if ($info['msg'] == CURLMSG_DONE) {
    $channel = $info['handle'];
    $page = array_search($channel, $this->pages);

    if($page !== false) {
        $this->pages[$page] = curl_multi_getcontent($channel);
        $this->multiHandlingRemove($channel);
    }

    curl_close($channel);
}

Here's a slightly improved version, for the giggles:

if ($info['msg'] == CURLMSG_DONE) {
    $channel = $info['handle'];

    if (isset($this->pages[$channel])) {
        $this->pages[$channel] = curl_multi_getcontent($channel);
        $this->multiHandlingRemove($channel);
    }

    curl_close($channel);
}

and here it is as a one-liner because I'm having fun with it (don't use it, it's not elegant in any sense):

if($info['msg'] == CURLMSG_DONE) isset($this->pages[$channel = $info['handle']]) && ($this->pages[$channel] = curl_multi_getcontent($channel) && $this->multiHandlingRemove($channel)) && curl_close($channel);

Upvotes: 1

Related Questions