PHP:在cookie中存储base_64数据
我需要在 cookie 中存储一些数据。数据经过 mcrypt
加密,然后经过 base64
以防止使用任何奇怪的字符。
存储加密的&会话中的编码字符串并将其读回&解密/解码工作完美。对 cookie 执行相同的操作会失败 - 返回完全乱码的文本。
显然,这是由于 mcrypt-decrypt
函数调用接收到不正确的数据,使我相信我的 cookie 内容以某种方式受到影响。
PHP 到底在幕后对我的 cookie 数据做什么?
代码:
(请注意,为了便于阅读,mcrypt 函数在下面表示为普通函数调用)
$string = base64_encode( mcrypt_encrypt( 'A string' ) );
setcookie('string', $string, time()+3600);
$_SESSION['string'] = $string;
$sessiondata = base64_decode( mcrypt_decrypt($_SESSION['string']); // A string!
$cookiedata = base64_decode( mcrypt_decrypt($_COOKIE['string']) ); // Completely gibberish
I need to store some data in a cookie. The data goes through mcrypt
encryption and then base64
to prevent any strange characters being used.
Storing the encrypted & encoded string in a session and reading it back & decrypting/decoding works perfectly. Doing the same to a cookie fails - completely gibberish text is returned.
Obviously this is due to the fact that the mcrypt-decrypt
function call receives improper data, making me to believe that the contents of my cookie are affected in one way or another.
What on earth is PHP doing behind the scenes to my cookie data?
Code:
(Note that the mcrypt-functions are represented below as plain function call for readability )
$string = base64_encode( mcrypt_encrypt( 'A string' ) );
setcookie('string', $string, time()+3600);
$_SESSION['string'] = $string;
$sessiondata = base64_decode( mcrypt_decrypt($_SESSION['string']); // A string!
$cookiedata = base64_decode( mcrypt_decrypt($_COOKIE['string']) ); // Completely gibberish
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在将字符串发送到 cookie 之前,尝试在字符串上调用 urlencode() ——我似乎记得,当数据在 $_COOKIE 中可用时,PHP 会自动对数据执行 urldecode() 。
Try calling urlencode() on your string before sending it to the cookie -- I seem to recall that PHP automatically does a urldecode() on the data when making it available in $_COOKIE.