Do not turn on the automatic serialization option of php redis extension

php redis extension has the option of automatic serialization. When storing kv data, you can open it with less code, and suddenly find a depressing place in the process of use.

The extension does not make type judgment on the value you want to store. Any type of value is automatically serialized, such as the following code


$rd = new Redis();
$r = $rd->connect(
    '127.0.0.1', 6379, 1
);
$rd->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
$rd->set('k', 1);
var_dump($rd->incr('k'));
echo $rd->getLastError(), PHP_EOL;
echo $rd->get('k');

You store an int, and then in incr, it fails


bool(false)
ERR value is not an integer or out of range

1

Directly use redis cli to see that the value has been serialized


127.0.0.1:6379> get k

"i:1;"

This is part of the code for php redis extension serialization (in library.c of the source package). You will find that this serialization does not make type judgment like memcached extension, but all serialization.


PHP_REDIS_API int
redis_serialize(RedisSock *redis_sock, zval *z, char **val, strlen_t *val_len
                TSRMLS_DC)
{
    ......
    switch(redis_sock->serializer) {
        case REDIS_SERIALIZER_NONE:
        ......
        case REDIS_SERIALIZER_PHP:
#if ZEND_MODULE_API_NO >= 20100000
            PHP_VAR_SERIALIZE_INIT(ht);
#else
            zend_hash_init(&ht, 10, NULL, NULL, 0);
#endif
            php_var_serialize(&sstr, z, &ht);
#if (PHP_MAJOR_VERSION < 7)
            *val = estrndup(sstr.c, sstr.len);
            *val_len = sstr.len;
#else
            *val = estrndup(ZSTR_VAL(sstr.s), ZSTR_LEN(sstr.s));
            *val_len = ZSTR_LEN(sstr.s);
#endif
            smart_str_free(&sstr);
#if ZEND_MODULE_API_NO >= 20100000
            PHP_VAR_SERIALIZE_DESTROY(ht);
#else
            zend_hash_destroy(&ht);
#endif
            return 1;
        case REDIS_SERIALIZER_IGBINARY:
        ......

    }
    return 0;
}

It seems that php redis has been extended for such a long time, with such a large number of users, but the documents have not entered the official ohp documents, which is not for no reason.

Keywords: Redis PHP less

Added by badal on Sat, 04 Jan 2020 10:04:25 +0200