php setcookie兼容ie,firefox

說明:文件編碼是gbk

 

function   escape_for_js($str)   {
          preg_match_all(“/[\x80-\xff].|[\x01-\x7f]+/”,$str,$r);
          $ar   =   $r[0];
          foreach($ar   as   $k=>$v)   {
              if(ord($v[0])   <   128)
                  $ar[$k]   =   urlRawDecode($v);
              else
                  $ar[$k]   =   “%u”.utf2ucs(iconv(“gbk”,”utf-8″,$v));//这里得用小写。如果用大写,会遇到繁体中文cookie乱码
          }
          return   join(“”,$ar);
    }

    function urlRawDecode($raw_url_encoded)
    {
        # Hex conversion table
        $hex_table = array(
            0 => 0x00,
            1 => 0x01,
            2 => 0x02,
            3 => 0x03,
            4 => 0x04,
            5 => 0x05,
            6 => 0x06,
            7 => 0x07,
            8 => 0x08,
            9 => 0x09,
            “A”=> 0x0a,
            “B”=> 0x0b,
            “C”=> 0x0c,
            “D”=> 0x0d,
            “E”=> 0x0e,
            “F”=> 0x0f
        );

        # Looking for latin characters with a pattern like this %C3%[A-Z0-9]{2} ie. -> %C3%B1 = ‘?’
        if(preg_match_all(“/\%C3\%([A-Z0-9]{2})/i”,$raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                    (0xc0 | ($hex_table[substr($value,0,1)]<<4)) | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = “%C3%” . $value;
            }

            $raw_url_encoded = str_replace($res,$arr_unicoded,$raw_url_encoded);
        }

        # Return raw url decoded
        return rawurldecode($raw_url_encoded);
    }

    function   utf2ucs($str){   
      //  echo $str,”
“;
        $n=strlen($str);   
        if   ($n==3)   {   
                $highCode   =   ord($str[0]);             
          $midCode   =   ord($str[1]);   
                $lowCode   =   ord($str[2]);   
          $a       =   0x1F   &   $highCode;   
          $b       =   0x7F   &   $midCode;   
          $c       =   0x7F   &   $lowCode;   
          $ucsCode   =   (64*$a   +   $b)*64   +   $c;       
        }   
        elseif   ($n==2)   {   
              $highCode   =   ord($str[0]);             
                $lowCode   =   ord($str[1]);   
          $a       =   0x3F   &   $highCode;     //0x3F是0xC0的补数   
          $b       =   0x7F   &   $lowCode;     //0x7F是0x80的补数   
          $ucsCode   =   64*$a   +   $b;       
        }   
        elseif($n==1)   {   
                $ucsCode   =   ord($str);   
        }   
        $ret =    dechex($ucsCode);   
       // echo $ret,”
“;
        return $ret;
      }
$a = “bbb轻音乐a輕”;
setcookie(“aaa”,escape_for_js($a));
?>

9 Comments