PHP Serialize() & Unserialize() Issues

表单序列化挑战
本文探讨了在处理大型表单时使用PHP的serialize和unserialize函数遇到的问题及解决方案。作者发现当表单字段包含特殊字符时,序列化会出现错误。通过使用base64编码解决此问题,确保了数据完整性和易于维护。

I've been working on some very large forms lately and I've come to the conclusion that creating a database scheme around them wouldn't be the best option because:

 

  1. My customers don't need to analyze all form submissions as a whole -- form information is simply used on a per-submission basis (like a job application, for example).
  2. Making updates to these forms would be very costly since it would take quite a bit of time to add and remove DB fields as well as update the HTML form.
  3. I'd like to revert the information into an array format just like it came in easily.

For that reason, I've been using the serialize() and unserialize() functions often. Serializing an array keeps the information in an array format, so to speak, but in one long string. Anyways, I ran into the following error when testing unserialize on some information that I had serialized:

Notice: unserialize(): Error at offset 2 of 52 bytes in file.php on line 130

 

It turns out that if there's a ", ', :, or ; in any of the array values the serialization gets corrupted. I've found the following fix for this issue on PHP.net:

//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));

//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));

 

It's a great fix to simple problem!

 

来源: http://davidwalsh.name/php-serialize-unserialize-issues

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值