unserialize

(PHP 4, PHP 5, PHP 7, PHP 8)

unserialize Crea un valor PHP a partir de una representación almacenada

Descripción

unserialize(string $str, array $options = ?): mixed

unserialize() toma una única variable serializada y la vuelve a convertir a un valor de PHP.

Advertencia

No pases valores no confiables proporcionados por el usuario a unserialize() con independencia del valor dado en options a allowed_classes. La deserialización puede resultar en que el código sea cargado y ejecutado debido a la instanciación y autocarga de objetos, y un usuario malicioso podría ser capaz de explotar este comportamiento. Utiliza un formato de intercambio de datos estándar y seguro como JSON (mediante json_decode() y json_encode()) si necesitas pasar datos serializados al usuario.

Si necesitas deserializar datos almacenados externamente, considera utilizar hash_hmac() para verificarlos. Asegúrate de que los datos no son modificados por nadie excepto por ti.

Parámetros

str

El string serializado.

Si la variable que está siendo convertida de vuelta es un objeto, PHP intentará llamar la función miembro __wakeup() si existe) automáticamente luego de haber recontruido satisfactoriamente el objeto.

Nota: Directiva unserialize_callback_func

Es posible establecer una función-llamada de retorno la cual será llamada si una clase no definida debería ser instanciada durante el proceso de revertir la seriación(para prevenir que se reciba un object incompleto "__PHP_Incomplete_Class".) Use su php.ini, ini_set() o .htaccess para definir unserialize_callback_func. Cada vez que una clase no definida deba ser instanciada, esta función será llamada. Para deshabilitar esta característica simplemente asigne un valor vacío a este parámetro.

options

Cualquier opción para unserialize(), dada como un array asociativo.

Opciones válidas
Nombre Tipo Descripción
allowed_classes mixed Puede ser un array de nombres de clases que deben ser aceptadas, false para no aceptar clases, o true para aceptar todas las clases. Si esta opción se define y unserialize() encuentra un objeto de una clase que no se acepta, el objeto será instanciado como __PHP_Incomplete_Class en su lugar. La omisión de esta opción es lo mismo que definirla como true: PHP intentará instanciar objetos de cualquier clase.

Valores devueltos

El valor convertido es retornado, y puede ser un boolean, integer, float, string, array u object.

En caso de que el string pasado no pueda ser procesado para revertir la serialización, se devuelve false y un error de tipo E_NOTICE es generado.

Historial de cambios

Versión Descripción
7.1.0 El elemento allowed_classes de options) es ahora estrictamente tipado, es decir: si cualquier cosa distinta de un array o un boolean es proporcionada, unserialize() retornará false y lanzará un E_WARNING.
7.0.0 Se añadió el parámetro options.
5.6.0 Manipular los datos serializados reemplazando C: con O: para forzar la instanciación de objetos sin llamar al constructor ahora fallará.

Ejemplos

Ejemplo #1 Ejemplo de unserialize()

<?php
// Aquí usamos unserialize() para cargar los datos de sesión
// provenientes del string seleccionado desde la base de datos en el
// array $datos_sesion. Este ejemplo complementa aquel descrito con serialize().

$con = odbc_connect("bd_web", "php", "gallina");
$sent = odbc_prepare($con, "SELECT datos FROM sesiones WHERE id = ?");
$datos_sql = array($_SERVER['PHP_AUTH_USER']);

if (!
odbc_execute($sent, &$datos_sql) || !odbc_fetch_into($sent, &$tmp)) {
// si la ejecución del comando o la recuperación de datos falla,
// inicializar una matriz vacía
$datos_sesion = array();
} else {
// ahora deberíamos tener los datos serializados en $tmp[0].
$datos_sesion = unserialize($tmp[0]);
if (!
is_array($datos_sesion)) {
// algo ha fallado, inicializar un array vacío
$datos_sesion = array();
}
}
?>

Ejemplo #2 Ejemplo de unserialize_callback_func

<?php
$objeto_seriado
='O:1:"a":1:{s:5:"valor";s:3:"100";}';

ini_set('unserialize_callback_func', 'mi_llamada_de_retorno'); // defina su callback_function

function mi_llamada_de_retorno($nombre_clase)
{
// tan solo incluya un fichero que contenga su definición de clase
// recibe $nombre_clase para determinar qué definición de clase requiere
}
?>

Notas

Advertencia

false es devuelto tanto en el caso de un error como cuando se convierte el valor seriado false. Es posible atrapar este caso especial comparando str con serialize(false) o atrapando el error E_NOTICE generado.

Ver también

add a note add a note

User Contributed Notes 24 notes

up
103
me+phpnet at unreal4u dot com
7 years ago
Just some reminder which may save somebody some time regarding the `$options` array:

Say you want to be on the safe side and not allow any objects to be unserialized... My first thought was doing the following:

<?php
$lol
= unserialize($string, false);
// This will generate:
// Warning: unserialize() expects parameter 2 to be array, boolean given
?>

The correct way of doing this is the following:
<?php
$lol
= unserialize($string, ['allowed_classes' => false]);
?>

Hope it helps somebody!
up
10
karsten at dambekalns dot de
3 years ago
Keep in mind that the allowed_classes does not use inheritance, i.e. allowing an interface is not possible and sub-classes won't pass the check. See https://3v4l.org/tdHfl
up
33
ErnestV
11 years ago
Just a note - if the serialized string contains a reference to a class that cannot be instantiated (e.g. being abstract) PHP will immediately die with a fatal error. If the unserialize() statement is preceded with a '@' to avoid cluttering the logs with warns or notices there will be absolutely no clue as to why the script stopped working. Cost me a couple of hours...
up
11
daniel at fourstaples dot com
14 years ago
Here's a simple function to get the class of a serialized string (that is, the type of object that will be returned if it's unserialized):

<?php
function get_serial_class($serial) {
   
$types = array('s' => 'string', 'a' => 'array', 'b' => 'bool', 'i' => 'int', 'd' => 'float', 'N;' => 'NULL');
   
   
$parts = explode(':', $serial, 4);
    return isset(
$types[$parts[0]]) ? $types[$parts[0]] : trim($parts[2], '"');
}
?>

I use this when saving a serialized object to a cookie, to make sure it is the right type when I go to unserialize it.

The type names are the same format/case as you would see if you did a var_dump().
up
9
hadley8899 at gmail dot com
4 years ago
For the people who are getting the error

PHP Notice:  unserialize(): Error at offset 191 of 285 bytes in ...

and are getting the data from a database, Make sure that you have the database set the the correct encoding, I had the database set as latin1_swedish_ci and all of the data looked perfect, Infact when i copied it into a online unserialize it worked fine. I changed the collation to utf8mb4_unicode_ci and all worked fine.
up
7
bjd
7 years ago
Talk on Exploiting PHP7 Unserialize here: https://media.ccc.de/v/33c3-7858-exploiting_php7_unserialize
up
5
chris at pollett dot org
9 years ago
When you serialize an object of a class from a particular namespace, the namespace is recorded as part of the serialization. If you decide to change this namespace's name, it can be hard to read in old serialized objects. I.e., suppose you had serialized an object of type foo\A, you change the namespace of your project to goo but otherwise leave the class definition of A unchanged. You would like to be able to unserialize the object as goo\A, instead unserialization will only create a partial object. To fix this in the case where you don't have nested objects in your class definition, you can use the following simple rename function:
/**
* Used to change the namespace of a serialized php object (assumes doesn't
* have nested subobjects)
*
* @param string $class_name new fully qualified name with namespace
* @param string $object_string serialized object
*
* @return string serialized object with new name
*/
function renameSerializedObject($class_name, $object_string)
{
    /*  number of digits in the length of name of the object needs to be
        less than 12 digits (probably more like 4) for this to work.
    */
    $name_length = intval(substr($object_string, 2, 14));
    $name_space_info_length = strlen("O:".$name_length.":") +
        $name_length + 2; // 2 for quotes;
    $object_string = 'O:' .
        strlen($class_name) . ':"'. $class_name.'"' .
        substr($object_string, $name_space_info_length);
    return $object_string;
}
up
10
Ray.Paseur often uses Gmail
11 years ago
In the Classes and Objects docs, there is this: In order to be able to unserialize() an object, the class of that object needs to be defined.

Prior to PHP 5.3, this was not an issue.  But after PHP 5.3 an object made by SimpleXML_Load_String() cannot be serialized.  An attempt to do so will result in a run-time failure, throwing an exception.  If you store such an object in $_SESSION, you will get a post-execution error that says this:

Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0

The entire contents of the session will be lost.  Hope this saves someone some time!

<?php // RAY_temp_ser.php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);
$_SESSION['hello'] = 'World';
var_dump($_SESSION);

// AN XML STRING FOR TEST DATA
$xml = '<?xml version="1.0"?>
<families>
  <parent>
    <child index="1" value="Category 1">Child One</child>
  </parent>
</families>'
;

// MAKE AN OBJECT (GIVES SimpleXMLElement)
$obj = SimpleXML_Load_String($xml);

// STORE THE OBJECT IN THE SESSION
$_SESSION['obj'] = $obj;
up
8
arbie samong
15 years ago
__PHP_Incomplete_Class Object Demystified

1. First take note of the output. A simple example:

__PHP_Incomplete_Class Object (
[__PHP_Incomplete_Class_Name] => SomeObject1
[obj1property1] => somevalue1 [obj1property2] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => SomeObject2 [obj2property1] => somevalue1 [obj2property2] => Array (
['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

2. We analyze this and break it down.
__PHP_Incomplete_Class Object tells you there is an object that needs to be declared somehow.
__PHP_Incomplete_Class_Name simply tells you the expected class name. It is just one of the properties for now.

So we have:
a) an unknown object that has a class name SomeObject1 (first class)
b) it has 2 properties, namely obj1property1 and obj2property2
c) obj2property2 is itself an object whose class name is SomeObject2 (the second class)
d) SomeObject2 has two properties, obj2property1 and obj2property2
e) obj2property2 is an array that contains two elements

3. Now that we have an idea of the structure, we shall create class definitions based from it. We will just create properties for now, methods are not required as a minimum.

<?php
class SomeObject1 {
        public
$obj1property1;
        public
$obj1property2;
}
class
SomeObject2 {
        public
$obj2property1;
        public
$obj2property2;
}
?>

4. Have that accessible to your script and it will solve the __PHP_Incomplete_Class Object problem as far as the output is concerned. Now you will have:

SomeObject1 ( [obj1property1] => somevalue1 [obj1property2] => SomeObject2 ( [obj2property1] => somevalue1 [obj2property2] => Array ( ['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

As you will notice, __PHP_Incomplete_Class Object is gone and replaced by the class name. The property __PHP_Incomplete_Class_Name is also removed.

5. As for the array property obj2property2, we can directly access that and just assume that it is an array and loop through it:

<?php

// this will be SomeObject1
$data = unserialize($serialized_data);

// this will be SomeObject2
$data2 = $data->obj1property2();

foreach(
$data2->obj2property2 as $key => $value):
         print
$key.' : '. $value .'<br>';
endforeach;

?>

Outputs:
key1 : somevalue3
key2 : somevalue4

That's it. You can add more methods on the class declarations for the given properties, provided you keep your original output as basis for the data types.
up
3
m.m.j.kronenburg
8 years ago
You can use the following code to use the php 7 unserialize function in php 5.3 and upwards. This adds the $option argument.

<?php

namespace
{

/**
* PHP 7 unserialize function for PHP 5.3 upwards.
* Added the $option argument (allowed_classes).
* See php unserialize manual for more detail.
**/
function php7_unserialize($str, $options = array())
{
  if(
version_compare(PHP_VERSION, '7.0.0', '>='))
  { return
unserialize($str, $options); }

 
$allowed_classes = isset($options['allowed_classes']) ?
   
$options['allowed_classes'] : true;
  if(
is_array($allowed_classes) || !$allowed_classes)
  {
   
$str = preg_replace_callback(
     
'/(?=^|:)(O|C):\d+:"([^"]*)":(\d+):{/',
      function(
$matches) use ($allowed_classes)
      {
        if(
is_array($allowed_classes) &&
         
in_array($matches[2], $allowed_classes))
        { return
$matches[0]; }
        else
        {
          return
$matches[1].':22:"__PHP_Incomplete_Class":'.
            (
$matches[3] + 1).
           
':{s:27:"__PHP_Incomplete_Class_Name";'.
           
serialize($matches[2]);
        }
      },
     
$str
   
);
  }
  unset(
$allowed_classes);
  return
unserialize($str);
}

}
// namespace

namespace my_name_space
{
 
/**
   * Use the new php7 unserialize in your namespace without
   * renaming all unserialize(...) function calls to
   * php7_unserialize(...).
   **/
 
function unserialize($str, $options = array())
  { return
php7_unserialize($str, $options); }
}

?>
up
8
chris AT cmbuckley DOT co DOT uk
16 years ago
As mentioned in the notes, unserialize returns false in the event of an error and for boolean false. Here is the first solution mentioned, without using error handling:

<?php
function isSerialized($str) {
    return (
$str == serialize(false) || @unserialize($str) !== false);
}

var_dump(isSerialized('s:6:"foobar";')); // bool(true)
var_dump(isSerialized('foobar'));        // bool(false)
var_dump(isSerialized('b:0;'));          // bool(true)
?>
up
2
w dot laurencine at teknoa dot net
15 years ago
When dealing with a string which contain "\r", it seems that the length is not evaluated correctly. The following solves the problem for me :

<?php
// remove the \r caracters from the $unserialized string
$unserialized = str_replace("\r","",$unserialized);

// and then unserialize()
unserialize($unserialized);
?>
up
2
chris at colourlovers dot com
13 years ago
Anyone having trouble serializing data with SimpleXMLElement objects stored within it, check this out:

This will traverse $data looking for any children which are instances of SimpleXMLElement, and will run ->asXML() on them, turning them into a string and making them serializable. Other data will be left alone.

<?php
function exportNestedSimpleXML($data) {
    if (
is_scalar($data) === false) {
        foreach (
$data as $k => $v) {
            if (
$v instanceof SimpleXMLElement) {
               
$v = str_replace("&#13;","\r",$v->asXML());
            } else {
               
$v = exportNestedSimpleXML($v);
            }

            if (
is_array($data)) {
               
$data[$k] = $v;
            } else if (
is_object($data)) {
               
$data->$k = $v;
            }
        }
    }

    return
$data;
}

$data = array (
   
"baz" => array (
       
"foo" => new stdClass(),
       
"int" => 123,
       
"str" => "asdf",
       
"bar" => new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>'),
    )
);

var_dump($data);
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    object(SimpleXMLElement)#4 (1) {
      [0]=>
      string(3) "bar"
    }
  }
}*/

var_dump(exportNestedSimpleXML($data));
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    string(54) "<?xml version="1.0" encoding="UTF-8"?>
<foo>bar</foo>
"
  }
}
*/
?>
up
3
BenBE at omorphia dot de
17 years ago
When trying to serialize or unserialize recursive arrays or otherwise linked data you might find the undocumented R data type quite useful.

If you want a array like the one produced with
<?
$a
= array();
$a[0] =& $a;
?>
serialized you can store it using a string simular to this one:
<?
$a
= unserialize("a:1:{i:0;R:1;}");
?>

Both sources will make $a hold an array that self-references itself in index 0.

The argument for R is the index of the created sub-variable of the serialize-string beginning with 1.
up
2
Are Pedersen
18 years ago
Be aware that if useing serialize/unserialize in a serverfarm with both 32bit and 64bit servers you can get unexpected results.

Ex: if you serialize an integer with value of 2147483648 on a 64bit system and then unserialize it on a 32bit system you will get the value -2147483648 instead. This is because an integer on 32bit cannot be above 2147483647 so it wraps.
up
2
double at dumpit dot com
17 years ago
This little function will check whether the serialized string is well formed.

PHP < 6 because i'd heard changes will be made in this php-intern function,
maybe it could be edited easy for it.

<?php

function wd_check_serialization( $string, &$errmsg )
{

   
$str = 's';
   
$array = 'a';
   
$integer = 'i';
   
$any = '[^}]*?';
   
$count = '\d+';
   
$content = '"(?:\\\";|.)*?";';
   
$open_tag = '\{';
   
$close_tag = '\}';
   
$parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";           
   
$preg = "/$parameter|($close_tag)/";
    if( !
preg_match_all( $preg, $string, $matches ) )
    {           
       
$errmsg = 'not a serialized string';
        return
false;
    }   
   
$open_arrays = 0;
    foreach(
$matches[1] AS $key => $value )
    {
        if( !empty(
$value ) && ( $value != $array xor $value != $str xor $value != $integer ) )
        {
           
$errmsg = 'undefined datatype';
            return
false;
        }
        if(
$value == $array )
        {
           
$open_arrays++;                               
            if(
$matches[3][$key] != '{' )
            {
               
$errmsg = 'open tag expected';
                return
false;
            }
        }
        if(
$value == '' )
        {
            if(
$matches[4][$key] != '}' )
            {
               
$errmsg = 'close tag expected';
                return
false;
            }
           
$open_arrays--;
        }
        if(
$value == $str )
        {
           
$aVar = ltrim( $matches[3][$key], '"' );
           
$aVar = rtrim( $aVar, '";' );
            if(
strlen( $aVar ) != $matches[2][$key] )
            {
               
$errmsg = 'stringlen for string not match';
                return
false;
            }
        }
        if(
$value == $integer )
        {
            if( !empty(
$matches[3][$key] ) )
            {
               
$errmsg = 'unexpected data';
                return
false;
            }
            if( !
is_integer( (int)$matches[2][$key] ) )
            {
               
$errmsg = 'integer expected';
                return
false;
            }
        }
    }       
    if(
$open_arrays != 0 )
    {
       
$errmsg = 'wrong setted arrays';
        return
false;
    }
    return
true;
}

?>
up
-1
OscarZarrus
2 years ago
For those who are looking for an efficient solution for handling controversial "FALSE", they can use this function which in case of non-unserializable string, instead of a "FALSE", throws an Exception. Vice versa it returns the unserialized variable.
<?php
   
/**
     * @param string $serializedString
     * @param array $options
     * @return mixed
     * @throws Exception
     */
   
function UnSerialize(string $serializedString, array $options = []) {
       
$_unserialized = @unserialize($serializedString, $options);
        if (
$serializedString === serialize(false) || $_unserialized !== false){
            return
$_unserialized;
        }
        throw new
Exception("Non-unserializable string");

    }

?>
up
1
Chris Hayes (chris at hypersites dot com)
20 years ago
In reply to the earlier post about having to include object definitions *before* using unserialize.  There is a workaround for this.

When an object is serialized, the first bit of the string is actually the name of the class.  When an unknown object is unserialized, this is maintained as a property.  So if you serialize it again, you get back the exact same string as if you'd serialized the original object.  Basically, to cut to the point...

If you use

$_SESSION['my_object'] = unserialize(serialize($_SESSION['my_object']))

then you get back an object of the correct type, even if the session had originally loaded it as an object of type stdClass.
up
1
suman dot jis at gmail dot com
12 years ago
I was getting unserialize()  Error at offset error.

If you face similar problem  then use the following procedure

$auctionDetails = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $dataArr[$i]['auction_details'] );
$auctionDetails = unserialize($auctionDetails);
up
-3
aderyn at nowhere dot tld
21 years ago
A quick note:
If you store a serialized object in a session, you have to include the class _before_ you initialize (session_start()) the session.
up
-3
Anonymous
5 years ago
If serialize() is the answer, you're almost certainly asking the wrong question.

JSON is widely available. The only thing it does not do, is the very thing that makes serialization immensely dangerous. All it takes is a crafty hacker to pass a crafted payload to a supposedly 'secured' serialize call, for a database driver to be overwritten with malicious code, for example.

Recreate the object. Normally. With actual data, and a source file, not with serialize. To do otherwise is laziness bordering on malice.
up
-6
MBa
13 years ago
To check if a string is serialized:

$blSerialized=(@unserialize($sText)||$sText=='b:0;');
up
-6
walf
13 years ago
a replacement for unserialize that returns whether it worked and populates the unserialized variable by reference:
<?php
function funserialize($serialized, &$into) {
    static
$sfalse;
    if (
$sfalse === null)
       
$sfalse = serialize(false);
   
$into = @unserialize($serialized);
    return
$into !== false || rtrim($serialized) === $sfalse;//whitespace at end of serialized var is ignored by PHP
}

$s_foo = 'b:0;';
var_dump(funserialize($s_foo, $foo), $foo);

$s_bar = 'bar';
var_dump(funserialize($s_bar, $bar), $bar);

$s_foo = 'a:0:{};';
var_dump(funserialize($s_foo, $foo), $foo);

?>
gives:

bool(true)
bool(false)

bool(false)
bool(false)

bool(true)
array(0) {
}
up
-11
Fagzal
14 years ago
To all who have problem with quoting and slashes when storing serialized data in MySQL: you are probably doing it wrong.

Use e.g. PDO with placeholders and the blob column type, and it will Just Work.
To Top