检查字符串是否已序列化? [英] Check to see if a string is serialized?

查看:127
本文介绍了检查字符串是否已序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定字符串是否是serialize()函数结果的最佳方法是什么?

What's the best way to determine whether or not a string is the result of the serialize() function?

https://www.php.net/manual/en/function.serialize

推荐答案

我会说,尝试 unserialize 它;-)

I'd say, try to unserialize it ;-)

引用手册:

如果传递的字符串不是 无法序列化,返回FALSE, 发出E_NOTICE.

In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.

因此,您必须检查返回值是否为false(使用===!==,以确保0null或其他没有问题)等于false,我会说).

So, you have to check if the return value is false or not (with === or !==, to be sure not to have any problem with 0 or null or anything that equals to false, I'd say).

请当心该通知:您可能希望/需要使用 @运算符.

Just beware the notice : you might want/need to use the @ operator.

例如:

$str = 'hjkl';
$data = @unserialize($str);
if ($data !== false) {
    echo "ok";
} else {
    echo "not ok";
}

将帮助您:

not ok


哦,就像@Peter所说的(感谢他!),如果您试图反序列化布尔false的表示,则可能会遇到麻烦:-(


EDIT : Oh, and like @Peter said (thanks to him!), you might run into trouble if you are trying to unserialize the representation of a boolean false :-(

因此,检查您的序列化字符串不等于"b:0;"也可能会有所帮助;我想像这样的东西应该可以解决问题:

So, checking that your serialized string is not equal to "b:0;" might be helpful too ; something like this should do the trick, I suppose :

$data = @unserialize($str);
if ($str === 'b:0;' || $data !== false) {
    echo "ok";
} else {
    echo "not ok";
}

在尝试反序列化之前测试这种特殊情况将是一种优化-但如果您不经常使用错误的序列化值,则可能没有太大用处.

testing that special case before trying to unserialize would be an optimization -- but probably not that usefull, if you don't often have a false serialized value.

这篇关于检查字符串是否已序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆