PHP 反序列化删除对象 属性

PHP Unserialize Removing Object Property

我有序列化 PDOException 的代码,通过网络发送它,然后再反序列化它。当我反序列化它时,$code 属性 似乎丢失了。对象的其余部分似乎没有变化。

我的代码是 运行 针对 PostgreSQL 数据库。使用以下 DDL:

CREATE TABLE test (
    id INTEGER
);

使用以下代码重现我的问题(替换为您自己的 PostgeSQL 连接值):

<?php

$dsn = "pgsql: dbname=postgres;host=/var/run/postgresql;port=5432";
$user = "postgres";
$password = "";
try
{
    $pdo = new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $res = $pdo->exec("INSERT INTO test (id) VALUES (999999999999999)");
}
catch (PDOException $e)
{
    var_dump((array) $e);
    print "\n";
    print $e->getCode();
    print "\n";
    $s = serialize($e);
    print $s;
    print "\n";
    $d = unserialize($s);
    var_dump((array) $d);
    print "\n";
    print $d->getCode();
    print "\n";
    print serialize($e->getCode());
    print "\n";
}

?>

在我的输出中,最终输出中缺少 $code 属性。此外,我收到以下通知:

PHP Notice: Undefined property: PDOException::$code in /home/developer/test_serialize.php on line 20

我发现我实际上必须执行一个失败的 SQL 语句才能看到这个问题。特别是如果我选择了错误的端口号,那么我会得到一个 PDOException 但它会在 unserialize 调用后保留 $code 属性。

请注意,序列化字符串似乎有代码 属性,所以我假设这是 unserialize 函数的问题。

任何见解都将不胜感激 - 我是否误解了这里的基本内容?这是 PHP 错误吗?还有别的吗?我使用以下 PHP 版本:

PHP 7.1.6 (cli) (built: Jun 18 2018 12:25:10) ( ZTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

编辑 - 添加打印输出

以下是复制脚本的输出。请注意,为了便于阅读,我稍微修改了一些换行符,并将 print_r 替换为 var_dump:

array(8) {
  ["*message"]=>
  string(75) "SQLSTATE[22003]: Numeric value out of range: 7 ERROR:  integer out of range"
  ["Exceptionstring"]=>
  string(0) ""
  ["*code"]=>
  string(5) "22003"
  ["*file"]=>
  string(34) "/home/developer/test_serialize.php"
  ["*line"]=>
  int(10)
  ["Exceptiontrace"]=>
  array(1) {
    [0]=>
    array(6) {
      ["file"]=>
      string(34) "/home/developer/test_serialize.php"
      ["line"]=>
      int(10)
      ["function"]=>
      string(4) "exec"
      ["class"]=>
      string(3) "PDO"
      ["type"]=>
      string(2) "->"
      ["args"]=>
      array(1) {
        [0]=>
        string(73) "INSERT INTO km_role (role_id, role_name) VALUES (999999999999999, 'test')"
      }
    }
  }
  ["Exceptionprevious"]=>
  NULL
  ["errorInfo"]=>
  array(3) {
    [0]=>
    string(5) "22003"
    [1]=>
    int(7)
    [2]=>
    string(28) "ERROR:  integer out of range"
  }
}

22003
O:12:"PDOException":8:{s:10:"*message";s:75:"SQLSTATE[22003]: Numeric value out of range: 7 ERROR:  integer out of range";s:17:"Exceptionstring";s:0:"";s:7:"*code";s:5:"22003";s:7:"*file";s:34:"/home/developer/test_serialize.php";s:7:"*line";i:10;s:16:"Exceptiontrace";a:1:{i:0;a:6:{s:4:"file";s:34:"/home/developer/test_serialize.php";s:4:"line";i:10;s:8:"function";s:4:"exec";s:5:"class";s:3:"PDO";s:4:"type";s:2:"->";s:4:"args";a:1:{i:0;s:73:"INSERT INTO km_role (role_id, role_name) VALUES (999999999999999, 'test')";}}}s:19:"Exceptionprevious";N;s:9:"errorInfo";a:3:{i:0;s:5:"22003";i:1;i:7;i:2;s:28:"ERROR:  integer out of range";}}
array(7) {
  ["*message"]=>
  string(75) "SQLSTATE[22003]: Numeric value out of range: 7 ERROR:  integer out of range"
  ["Exceptionstring"]=>
  string(0) ""
  ["*file"]=>
  string(34) "/home/developer/test_serialize.php"
  ["*line"]=>
  int(10)
  ["Exceptiontrace"]=>
  array(1) {
    [0]=>
    array(6) {
      ["file"]=>
      string(34) "/home/developer/test_serialize.php"
      ["line"]=>
      int(10)
      ["function"]=>
      string(4) "exec"
      ["class"]=>
      string(3) "PDO"
      ["type"]=>
      string(2) "->"
      ["args"]=>
      array(1) {
        [0]=>
        string(73) "INSERT INTO km_role (role_id, role_name) VALUES (999999999999999, 'test')"
      }
    }
  }
  ["Exceptionprevious"]=>
  NULL
  ["errorInfo"]=>
  array(3) {
    [0]=>
    string(5) "22003"
    [1]=>
    int(7)
    [2]=>
    string(28) "ERROR:  integer out of range"
  }
}

PHP Notice:  Undefined property: PDOException::$code in /home/developer/test_serialize.php on line 24

s:5:"22003"

在通过错误的端口号抛出 PDOException 的示例中,序列化的 $e->getCode() 是:

i:7;

首先看一下 PDOException class:

PDOException extends RuntimeException {
  /* Properties */
  public array $errorInfo ;
  protected string $code ;

  /* Inherited properties */
  protected string $message ;
  protected int $code ;
  protected string $file ;
  protected int $line ;

  /* Inherited methods */
  final public string Exception::getMessage ( void )
  final public Throwable Exception::getPrevious ( void )
  final public mixed Exception::getCode ( void )
  final public string Exception::getFile ( void )
  final public int Exception::getLine ( void )
  final public array Exception::getTrace ( void )
  final public string Exception::getTraceAsString ( void )
  public string Exception::__toString ( void )
  final private void Exception::__clone ( void )
}

PHP中的getCode()方法是这样实现的(ref: https://github.com/php/php-src/blob/cd953269d3d486f775f1935731b1d6d44f12a350/ext/spl/spl.php):

/** @return the code passed to the constructor
 */
final public function getCode()
{
    return $this->code;
}

这是PHP异常的构造函数:

/** Construct an exception
 *
 * @param $message Some text describing the exception
 * @param $code    Some code describing the exception
 */
function __construct($message = NULL, $code = 0) {
    if (func_num_args()) {
        $this->message = $message;
    }
    $this->code = $code;
    $this->file = __FILE__; // of throw clause
    $this->line = __LINE__; // of throw clause
    $this->trace = debug_backtrace();
    $this->string = StringFormat($this);
}

这告诉我们什么? Exception的$code 属性只能在Exception产生时填充,如果没有传递$code,它应该为零。

这是 PHP 错误吗?我猜不是,经过一些研究我发现了以下很棒的文章:http://fabien.potencier.org/php-serialization-stack-traces-and-exceptions.html

本质上说:

当PHP序列化异常时,它会序列化异常代码、异常消息以及堆栈跟踪。

堆栈跟踪是一个数组,其中包含脚本此时已执行的所有函数和方法。跟踪包含文件名、文件中的行、函数名和传递给函数的所有参数的数组。你发现问题了吗?

堆栈跟踪包含对 PDO 实例的引用,因为它已传递给 will_crash() 函数,并且由于 PDO 实例不可序列化,因此在 PHP 序列化时抛出异常堆栈跟踪。

Whenever a non-serializable object is present in the stack trace, the exception won't be serializable.

我想这就是我们的 serialize()/unserialize() 过程失败的原因——因为异常不可序列化。

解法:

Write a Serializable Exception which extends Exception

class SerializableException extends Exception implements Serializable {
// ... go ahead :-)
}

Blackbam 的回答很特别,但不可序列化的 PDO 对象是一个转移注意力的问题。您的代码的问题实际上是由于 $code 属性 的类型造成的,正如在对他的 post 的评论中所讨论的那样。在某些情况下,异常是用错误代码的字符串表示而不是整数来初始化的。这破坏了反序列化,反序列化非常合理地决定丢弃具有无效类型的属性。

PDOException documentation page上的评论几乎都是在讨论错误代码被创建为字符串而不是整数引起的问题。

您可以使用反射将受保护的值设置为整数。见下文:

try
{
    $pdo = new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $res = $pdo->exec("INSERT INTO test_schema.test (id) VALUES (999999999999999)");
}
catch (PDOException $e)
{
    // the new bit is here
    if (!is_int($e->getCode())) {
        $reflectionClass = new ReflectionClass($e);
        $reflectionProperty = $reflectionClass->getProperty('code');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($e, (int)$reflectionProperty->getValue($e));    
    }
    // the rest is the same
    var_dump((array) $e);
    print "\n";
    print $e->getCode();
    print "\n";
    $s = serialize($e);
    print $s;
    print "\n";
    $d = unserialize($s);
    var_dump((array) $d);
    print "\n";
    print $d->getCode();
    print "\n";
    print serialize($e->getCode());
    print "\n";
}

当然,如果代码包含字母数字值而不是转换为字符串的整数,您将丢失信息。该消息可能会重复错误编号,但这可能不太可靠。

如果您稍微调整一下代码,Blackbam 关注的不可序列化堆栈跟踪可能会成为一个问题:

function will_crash($pdo) {
    $res = $pdo->exec("INSERT INTO test_schema.test (id) VALUES (999999999999999)");
}

try
{
    $pdo = new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    will_crash($pdo);
}
catch (PDOException $e)
{
    $s = serialize($e);
    // PHP Fatal error:  Uncaught PDOException: You cannot serialize or unserialize PDO instances in...
}

糟糕。

所以 Blackbam 的回答,以及他 link 中创建可序列化异常 class 的方法可能是可行的方法。这允许您序列化异常的数据而不是堆栈跟踪。

话又说回来,到时候你还不如直接用json_encodejson_decode来传递around/store异常信息。