how to store serialized object with namespace in database using pdo php

前端 未结 2 1270
自闭症患者
自闭症患者 2021-01-25 23:42

When i try to store serialized object with namespace i cant do that beacuse i got error unterminated quoted string at or near \"\'O:22:\"protect\\classes\\Router\". Code:

<
2条回答
  •  醉话见心
    2021-01-26 00:21

    I was facing same problem - and found out here that this is the zer-byte problems. After some development I created an adapter for Zend Serializer (ZF2) that overloads serialize/unserialize methods in a way that it will be possible to store these serialized values in PostgreSQL.

    The code you can find below - hopefully it will somehow useful :)

    use Zend\Serializer\Adapter\PhpSerialize;
    
    /**
     *
     * Class overloads serialization methods so serialized objects will be PostgreSQL safe
     * For further information on safe/unsafe objects:
     * http://php.net/manual/en/function.serialize.php#96504
     *
     */
    class PostgresSerialize extends PhpSerialize {
    
        const DEFAULT_SAFE_NULLBYTE_REPLACEMENT = "~~NULL_BYTE~~";
    
        protected static $serializedFalse = null;
    
        public function serialize($value) {
            $serializedString = parent::serialize($value);
            if (strpos($this->options['safe_nullbyte_replacement'], $serializedString))
                throw new \RuntimeException('Cannot perform safe nullbyte replace operation since safe_nullbyte_replacement="' .  $this->options['safe_nullbyte_replacement'] . '"value already exists in the serialized string', \Zend\Log\Logger::ERR);
            if ($this->options['safe_nullbyte_replacement'] == null)
                $this->options['safe_nullbyte_replacement'] = self::DEFAULT_SAFE_NULLBYTE_REPLACEMENT;
            return str_replace("\0", $this->options['safe_nullbyte_replacement'], $serializedString);
        }
    
        public function unserialize($serialized) {
            if ($this->options['safe_nullbyte_replacement'] == null)
                $this->options['safe_nullbyte_replacement'] = self::DEFAULT_SAFE_NULLBYTE_REPLACEMENT;
            $serializedString = str_replace($this->options['safe_nullbyte_replacement'], "\0", $serialized);
            return parent::unserialize($serializedString);
        }
    
    }
    

提交回复
热议问题