PHP deserialization

Keywords: Web Security

1, Pre knowledge

1. Basic concepts

A class definition starts with the keyword class, followed by the name of the class. The body of a class is contained in a pair of curly braces, which contain the definition of class properties and methods.

Class attributes exist in the data segment and class methods exist in the code segment. For a class, class methods do not occupy class space, and only class attributes occupy space.

2. Grammar

To create an instance of a class, you must use the new keyword. When creating a new object, the object is always assigned unless the object defines a constructor and throws an exception when an error occurs. Classes should be defined before being instantiated (which is necessary in some cases).

If new is followed by a string containing the class name, an instance of the class is created. If the class belongs to a namespace, its full name must be used.

//Create an instance
<?php
$instance = new SimpleClass();

// You can also do this:
$className = 'Kin';
$instance = new $className(); // Kin()
?>

2, Serialization

If a script wants to call the variables of the previous script, but the previous script has been executed and all variables and contents have been released, how do we operate?

Serialize and unserialize solve this problem. Serialize can convert variables into strings, and save the value of the current variable in the conversion; Unserialize can transform the string generated by serialize back to a variable.

1,serialize()

All values in php can be represented by using the function serialize() to return a string containing a byte stream. Serializing an object will save all variables of the object, but will not save the method of the object, but only the name of the class.

  It can be understood as follows:

At the end of program execution, the memory data will be destroyed immediately. The data stored in variables is memory data, and files and databases are "persistent data". Therefore, PHP serialization is the process of "saving" the variable data in memory to the persistent data in files.

 

For example, chestnuts:

<?php
class User
{
  public $age = 0;
  public $name = ''; 
  public function PrintData()
  {
    echo 'User '.$this->name.' is'.$this->age.' years old. <br />';
  }
}

//Create an object
$user = new User();

// Set data
$user->age = 17;
$user->name = 'kinyoobi';

//output data
$user->PrintData();

//Output serialized data
echo serialize($user);
?>

result:

O indicates the object type, 4 indicates that the object name is 4 in length, User is the class name, and 2 indicates that there are two parameters;

{} inside is the key and value of the parameter: s means string type, 3 means length, and age is key; i indicates integer type and 17 is value.

a array b boolean
d
double i integer
o common object r reference
s string C custom object
O class N null
R pointer reference U unicode string

2,unserialize()

Deserialization is the process of restoring serialization formatted stored characters to objects.

Note: before deserializing an object, the class of the object must be defined before deserialization. Otherwise, an error will be reported

 

For example, chestnuts:

<?php
class User
{
  public $age = 0;
  public $name = '';
  public function PrintData()
  {
    echo 'User '.$this->name.' is '.$this->age.' years old. <br />';
  }
}
//Rebuild object
$user = unserialize('O:4:"User":2:{s:3:"age";i:17;s:4:"name";s:8:"kinyoobi";}');
$user->PrintData();
?>

result:

3. Magic method

PHP will all__ Class methods starting with (two underscores) remain magic methods and will be called under specific circumstances.

__construct  Constructor
__destruct Triggered when the object is destroyed, destructor
__toString Triggered when a class is used as a string
__wakeup() unserialize before calling for pre - Preparation of object resources
__sleep()  serialize prior call
__call() Triggering an invocable method in an object context
__callStatic()  Triggering an invocable method in a static context
__get()  Called when trying to read a property that does not exist
__set()  Used to write data to inaccessible properties
__isset() Triggered by calling isset() or empty() on an inaccessible property
__unset()  Triggered when unset() is used on an inaccessible property
__invoke() Triggered when a script attempts to call an object as a function

4. Two magic methods related to serialization

1)__sleep()

The serialize() function checks whether a magic method exists in the class__ sleep(). If present__ Sleep(), the magic method will be called first, and then the serialization operation will be performed.

This function can be used to clean up an object and return an array containing the names of all variables in the object that should be serialized. If the method returns nothing, NULL is serialized and an e is generated_ Note level error.

2)__wakeup()

The unserialize() function checks to see if there is one__ wakeup() method. If it exists, it will be called first__ The wakeup method prepares the resources required by the object in advance.

__ wakeup() is often used in deserialization operations, such as re establishing a database connection or performing other initialization operations.

 

For example, chestnuts:

<?php
 class test{
 public $varr1="abc";
 public $varr2="123";
 
 public function echoP(){
 echo $this->varr1."<br>";
 }

 public function __construct(){
 echo "__construct<br>";
 }

 public function __destruct(){
 echo "__destruct<br>";
 }

 public function __toString(){
 return "__toString<br>";
 }

 public function __sleep(){
 echo "__sleep<br>";
 //return array('varr1','varr2');
 return array('varr1');
 }

 public function __wakeup(){
 echo "__wakeup<br>";
 }
}

$obj = new test();  //Instantiate object, call__ construct() method, output__ construct
$obj->echoP();  //Call the echo () method and output "abc"
echo $obj;  //obj object is output as a string and called__ toString() method, output__ toString
$s =serialize($obj);  //obj object is serialized and called__ sleep() method, output__ sleep
var_dump($s);
echo "<br>";
$u = unserialize($s);  //$s will be deserialized first and will call__ wake() method
var_dump($u);
echo "<br>";
// When the script ends, it will call again__ destruct() method, output__ destruct

?>

result:

When serializing__ sleep returns varr1 to clean up the data; During deserialization, that is, when the class is restored to an object, the class properties of the class itself cannot be destroyed, so varr1 and varr2 will be printed in the end.

 

  reference resources:

https://www.cnblogs.com/ichunqiu/p/10484832.html

https://www.php.cn/php-weizijiaocheng-454909.html

 

Posted by vandana on Thu, 25 Nov 2021 22:38:51 -0800