PHP base64编码后解码乱码的解决办法
在用PHP做东西的时候发现了一个问题,可以简单的归结为乱码的问题,但是这个问题不是函数本身造成的。来看看罪魁祸首是谁。
嫌疑人:base64_encode和base64_decode
罪行:我写了一个跳转和提示函数,接收提示信息后跳转到指定的页面,但是跳转提示时汉字乱码。
跳转模版代码如下:
<!DOCTYPEhtml><html><head><metacharset="utf-8"><metaname="author"content="王健wj@yurendu.com"/>
<title>跳转提示</title>
<styletype="text/css">
*{padding:0;margin:0;}
body{background:#fff;font-family:'微软雅黑';color:#333;font-size:16px; text-align:center;}
.system-message{width:600px;margin:150pxauto0auto;background:#f8f8f8;border:1pxsolid#ccc;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;-webkit-box-shadow:#6660px0px10px;-moz-box-shadow:#6660px0px10px;box-shadow:#6660px0px10px;}
.system-messageh1{font-size:30px;font-weight:normal;height:100px;line-height:100px;color:#c60;}
.system-message.jump{padding:40px0;}
.system-message.jumpa{color:#333;}
.system-message.success,.system-message.error{height:60px;line-height:70px;font-size:18px;color:#900;}
.system-message.detail{font-size:12px;line-height:20px;margin-top:12px;display:none}
</style>
</head>
<body>
<divclass="system-message">
<?phpif($_GET['success']){?>
<h1>:) 恭喜!</h1>
<pclass="success"><?phpechobase64_decode($_GET['message']);?></p>
<?php}else{?>
<h1>:( 出错了!</h1>
<pclass="error"><?phpechobase64_decode($_GET['message']);?></p>
<?php}?>
<pclass="detail"></p>
<pclass="jump">系统将在<bid="wait"><?phpecho$_GET['time'];?></b>后跳转,可直接<aid="href"href="<?phpechobase64_decode($_GET['url']);?>">点此跳转</a></p>
</div>
<scripttype="text/javascript">
(function(){
varwait=document.getElementById('wait'),href=document.getElementById('href').href;
varinterval=setInterval(function(){
vartime=--wait.innerHTML;
if(time<=0){
location.href=href;
clearInterval(interval);
};
},1000);
})();
</script>
</body>
</html>
PHPredirect函数定义如下:
/*提醒后跳转*/
function_alert($success=true,$message='success',$time='3',$url='/'){
header('Location:/include/redirect.php?success='.$success.'&message='.base64_encode($message).'&time='.$time.'&url='.base64_encode($url));
exit;
}
假如在PHP中这样调用函数的话:
$query="updatecontentsetbid='$clean[bid]',title='$clean[title]',content='$clean[content]',path='$clean[path]'whereid=".$clean['id'];
if(mysql_query($query)){
_alert(1,'修改成功',3,'/admin/manage.php');
}else{
_alert(false,'修改失败'.mysql_error(),5,'/admin/manage.php');
}
你就会看到,“修改成功”或者是“修改失败”这几个汉字乱码了。
为什么?
有时候用base64_encode加密后,以GET的形式传到其他页面,用base64_decode解密的时候,出现乱码。
遇到这个问题的时候,我就纳闷了,为什么有一些能正确解密,但是有一些却出现乱码呢?
后来经过检查,发现有一些中文字符,用GET形式传过来的时候,+号会被替换成空格。
为了防止出现乱码的情况,我做了一步替换,然后再解密,果然,乱码的问题,不复存在了!
现在问题已经很简单了,只要多写一步就好了
$str=base64_decode(str_replace("","+",$_GET['str']));
原来,文章一开始定错了嫌疑人了,冤枉了那两个函数了。。。
还可以参考这篇文章:PHP安全的URL字符串base64编码和解码