Home Backend Development PHP Tutorial php中unserialize返回false的解决方法_php技巧

php中unserialize返回false的解决方法_php技巧

May 16, 2016 pm 08:36 PM
false php unserialize Solution return

本文实例讲述了php中unserialize返回false的解决方法,分享给大家供大家参考。具体方法如下:

php 提供serialize(序列化) 与unserialize(反序列化)方法。
使用serialize序列化后,再使用unserialize反序列化就可以获取原来的数据。

先来看看如下程序实例:

<&#63;php 
$arr = array( 
  'name' => 'fdipzone', 
  'gender' => 'male' 
); 
 
$str = serialize($arr); //序列化 
echo 'serialize str:'.$str."\r\n\r\n"; 
 
$content = unserialize($str); // 反序列化 
echo "unserialize str:\r\n"; 
var_dump($content); 
&#63;> 

Copy after login

输出:

serialize str:a:2:{s:4:"name";s:8:"fdipzone";s:6:"gender";s:4:"male";} 
 
unserialize str: 
array(2) { 
 ["name"]=> 
 string(8) "fdipzone" 
 ["gender"]=> 
 string(4) "male" 
} 

Copy after login

但下面这个例子反序列化会返回false

<&#63;php 
$str = 'a:9:{s:4:"time";i:1405306402;s:4:"name";s:6:"新晨";s:5:"url";s:1:"-";s:4:"word";s:1:"-";s:5:"rpage";s:29:"http://www.baidu.com/test.html";s:5:"cpage";s:1:"-";s:2:"ip";s:15:"117.151.180.150";s:7:"ip_city";s:31:"中国北京市 北京市移动";s:4:"miao";s:1:"5";}'; 
var_dump(unserialize($str)); // bool(false) 
&#63;> 

Copy after login

检查序列化后的字符串,发现出问题是在两处地方:

s:5:"url"
s:29:"http://www.baidu.com/test.html"
这两处应为
s:3:"url"
s:30:"http://www.baidu.com/test.html"

出现这种问题的原因是序列化数据时的编码与反序列化时的编码不一致导致,例如数据库是latin1和UTF-8字符长度不一样。
另外有可能出问题的还有单双引号,ascii字符"\0"被解析为 '\0',在C中是字符串的结束符等于chr(0),错误解析后算了2个字符。
\r在计算长度时也会出问题。

解决方法如下:

// utf8 
function mb_unserialize($serial_str) { 
  $serial_str= preg_replace('!s:(\d+):"(.*&#63;)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str ); 
  $serial_str= str_replace("\r", "", $serial_str); 
  return unserialize($serial_str); 
} 
 
// ascii 
function asc_unserialize($serial_str) { 
  $serial_str = preg_replace('!s:(\d+):"(.*&#63;)";!se', '"s:".strlen("$2").":\"$2\";"', $serial_str ); 
  $serial_str= str_replace("\r", "", $serial_str); 
  return unserialize($serial_str); 
} 

Copy after login

例子:

echo '<meta http-equiv="content-type" content="text/html; charset=utf-8">'; 
 
// utf8 
function mb_unserialize($serial_str) { 
  $serial_str= preg_replace('!s:(\d+):"(.*&#63;)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str ); 
  $serial_str= str_replace("\r", "", $serial_str); 
  return unserialize($serial_str); 
} 
 
$str = 'a:9:{s:4:"time";i:1405306402;s:4:"name";s:6:"新晨";s:5:"url";s:1:"-";s:4:"word";s:1:"-";s:5:"rpage";s:29:"http://www.baidu.com/test.html";s:5:"cpage";s:1:"-";s:2:"ip";s:15:"117.151.180.150";s:7:"ip_city";s:31:"中国北京市 北京市移动";s:4:"miao";s:1:"5";}'; 
 
var_dump(unserialize($str));  // false 
 
var_dump(mb_unserialize($str)); // 正确 

Copy after login

使用处理过单双引号,过滤\r的mb_unserialize方法就能成功反序列化了。

使用unserialize:

bool(false)

使用mb_unserialize

array(9) { 
 ["time"]=> 
 int(1405306402) 
 ["name"]=> 
 string(6) "新晨" 
 ["url"]=> 
 string(1) "-" 
 ["word"]=> 
 string(1) "-" 
 ["rpage"]=> 
 string(30) "http://www.baidu.com/test.html" 
 ["cpage"]=> 
 string(1) "-" 
 ["ip"]=> 
 string(15) "117.151.180.150" 
 ["ip_city"]=> 
 string(31) "中国北京市 北京市移动" 
 ["miao"]=> 
 string(1) "5" 
}

Copy after login

希望本文所述对大家PHP程序设计的学习有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles