Definite guide to valid Cookie values

前端 未结 2 1458
失恋的感觉
失恋的感觉 2020-12-29 13:51

I know there are other questions but they seem to have answers which are assumptions rather than being definitive.

My limited understanding is that cookie values are

2条回答
  •  一生所求
    2020-12-29 14:24

    There was the mention of base64, so here is a cooked cookie solution using that in cookies. The functions are about a modified version of base64, they only use [0-9a-zA-Z_-]

    You can use it for both the name and value part of cookies, is binary safe, as they say.

    The gzdeflate/gzinflate takes back 30% or so space created by base64, could not resist using it. Note that php gzdeflate/gzinflate is only available in most hosting companies, not all.

    //write
    setcookie
             (
             'mycookie'
             ,code_base64_FROM_bytes_cookiesafe(gzdeflate($mystring))
             ,time()+365*24*3600
             );
    //read
    $mystring=gzinflate(code_bytes_FROM_base64_cookiesafe($_COOKIE['mycookie']));
    
    
    function code_base64_FROM_bytes_cookiesafe($bytes)
        {
        //safe for name and value part [0-9a-zA-Z_-]
        return strtr(base64_encode($bytes),Array
                (
                '/'=>'_',
                '+'=>'-',
                '='=>'',
                ' '=>'',
                "\n"=>'',
                "\r"=>'',
                ));
        }
    
    
    function code_bytes_FROM_base64_cookiesafe($enc)
        {
        $enc=str_pad($enc,strlen($enc)%4,'=',STR_PAD_RIGHT);//add back =
        $enc=chunk_split($enc);//inserts \r\n every 76 chars
        return base64_decode(strtr($enc,Array
                (
                '_'=>'/',
                '-'=>'+',
                )));
        }
    

提交回复
热议问题