dflydev / dflydev-fig-cookies

Cookies for PSR-7 HTTP Message Interface.
MIT License
224 stars 29 forks source link

TypeError on urldecode() with malformed cookie #41

Closed proton-ab closed 3 years ago

proton-ab commented 3 years ago

There is an issue in splitCookiePair where malformed pair is given without =, the result is a call on urldecode with first parameter as NULL.

Example code:

<?php

declare(strict_types=1);

namespace Dflydev\FigCookies;

use function array_filter;
use function assert;
use function explode;
use function is_array;
use function preg_split;
use function urldecode;

class StringUtil
{
    /** @return string[] */
    public static function splitOnAttributeDelimiter(string $string) : array
    {
        $splitAttributes = preg_split('@\s*[;]\s*@', $string);

        assert(is_array($splitAttributes));

        return array_filter($splitAttributes);
    }

    /** @return string[] */
    public static function splitCookiePair(string $string) : array
    {
        $pairParts    = explode('=', $string, 2);
        $pairParts[1] = urldecode($pairParts[1]) ?? '';

        return $pairParts;
    }
}

var_dump(StringUtil::splitCookiePair('cookie=value'));
var_dump(StringUtil::splitCookiePair('cookie='));
var_dump(StringUtil::splitCookiePair('cookie')); // urldecode() expects parameter 1 to be string, null given

While the cookie string is malformed if = is missing before ;, the code should definitely not fail catastrophically in this case.