• PHP Video Tutorials

PHP - unserialize() Function



Definition and Usage

The function unserialize() converts the serialized data back to normal PHP value.

Syntax

mixed unserialize ( string $data , array $options = [] )

Parameters

Sr.No Parameter Description
1

data

Mandatory. This specifies the serialized string.

2

options

Optional. Any options to be provided to unserialize(), as an associative array. Can be either an array of class names which can be accepted, false to accept no classes, or true to accept all classes. true is default.

Return Values

This function returns converted value which can be a bool, int, float, string, array or object. Suppose passed string is not unserializeable, false is returned and E_NOTICE is issued.

Dependencies

PHP 4 and above.

Example

Following example demonstrates first serializing and the unserializing the data:

<?php
  class test1{
     private $name;
     function __construct($arg){
        $this->name=$arg;
     }
     function getname(){
        return $this->name;
     }
  }
  $obj1=new test1("tutorialspoint");
  $str=serialize($obj1); //first serialize the object and save to a file test,txt
  $fd=fopen("test.txt","w");
  fwrite($fd, $str);
  fclose($fd);

  $filename="test.txt";
  $fd=fopen("test.txt","r");
  $str=fread($fd, filesize($filename));
  $obj=unserialize($str);
  echo "name: ". $obj->getname();
?>

Output

This will produce following result −

name: tutorialspoint
Advertisements