nginx userid 模块客户端 cookie 解码

在网上看到用 ruby 解码的一段程序

http://forum.nginx.org/read.php?2,52592,52592

cookie_uid = "0Cvz4ktwVPEdbRcMAwMFAg=="; cc = cookie_uid.unpack('m*').first; rr = cc.split("").map{|c| c[0].to_i}.inject([]) {|v,s| v.push sprintf("%02X", s); v; }.values_at(3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12).join("")

=> "E2F32BD0F154704B0C176D1D02050303"

我用 PHP 写了一个

<?php
function nginx_userid_decode($str)
{
    $str_unpacked =  unpack('h*', base64_decode(str_replace(' ', '+', $str)));
    $str_split = str_split(current($str_unpacked), 8);
    $str_map = array_map('strrev', $str_split);
    $str_dedoded = strtoupper(implode('', $str_map));
 
    return $str_dedoded;
}
 
// uid=8380A8C09A7E8C4B0A112CC202030303
echo nginx_userid_decode('wKiAg0uMfprCLBEKAwMDAg==');

如果 base64 后的编码中含有 '+' , 在 url 传递中或是 $_COOKIE 数组读取中会被转换为空格

2010-04-12 200 base64 decode nginx php ruby