if (!function_exists('getEncryption')) { /** * 基于base64的数据加密 * @param $data * @return string */ function getEncryption($data){ return base64_encode(gzcompress(serialize($data))); } } if (!function_exists('unEncryption')) { /** * 解密 * @param $str * @return mixed */ function unEncryption($str){ return unserialize(gzuncompress(base64_decode($str))); } }
示例:
代码:
$arr = [ 'a'=>[ 'dfhs213214214214kldfhsalkfjdfhs213214214214kldfhsalkfjdfhs213klddfsfggasdfasfagsgsfdsfadsakfaslkjffs', 'dfhs213214214214kldfhsalkfjdfhs213214214214kldfhsalkfjdfhs213klddfsfggasdfasfagsgsfdsfadsakfaslkjffs' ], 'b'=>'dfhs213214214214kldfhsalkfjdfhs213214214214kldfhsalkfjdfhs213klddfsfggasdfasfagsgsfdsfadsakfaslkjffs', 'c'=>'dfhs213214214214kldfhsalkfjdfhs213214214214kldfhsalkfjdfhs213klddfsfggasdfasfagsgsfdsfadsakfaslkjffs', 'd'=>'dfhs213214214214kldfhsalkfjdfhs213214214214kldfhsalkfjdfhs213klddfsfggasdfasfagsgsfdsfadsakfaslkjffs', 'e'=>'dfhs213214214214kldfhsalkfjdfhs213214214214kldfhsalkfjdfhs213klddfsfggasdfasfagsgsfdsfadsakfaslkjffs', ]; $json = json_encode($arr); echo strlen($json).PHP_EOL; // 长度:641 //加密 $encryption = base64_encode(gzcompress(serialize($json))); echo $encryption.PHP_EOL; // eJy9j7ENgDAQA3f5miYBUYRREMXD4yCSziVid4IYgO4lF9a5OJlpHEKSS1TSLIaDMfQxDF9KfYnWgvN/asRA5Kw0KKGZmbBWjFoaqeUEKJ2PZulkleR1afNTmZ9q91LdMj1+Sd35 echo strlen($encryption).PHP_EOL; // 长度:136 //解密 $decrypt = unserialize(gzuncompress(base64_decode($encryption))); print_r(json_decode($decrypt,true));
结果:
压缩长度非固定,视情况使用!
php 有以下压缩字符串函数:
- gzcompress 速度最快,压缩比率较高。
- gzdeflate 压缩比率最高,速度稍慢于gzcompress
- gzencode 与 gzdeflate 比较接近,gzdeflate稍有优势
- bzcompress 速度最慢,压缩比率最慢。
建议使用 gzcompress 和 gzdeflate。