The __PHP_Incomplete_Class Trap in Session Handlers
Encountering __PHP_Incomplete_Class objects in your $_SESSION array is a classic PHP gotcha that stems from a specific order-of-operations violation. When you attempt to serialize an object before its class definition is fully loaded, the serialization mechanism cannot access the class schema required to reconstruct that object later. Instead of storing the full object data, it stores a placeholder. Upon unserializationâtypically at the start of a new requestâPHP tries to instantiate this placeholder but fails because the class isn't recognized as valid in the current context, resulting in the incomplete class warning and a corrupted session state.
In your specific scenario, you are wrapping user input into SafeString objects to mitigate XSS risks. This is a valid defensive strategy, but it introduces a hard dependency on the timing of class inclusion relative to session handling. Your code attempts to process the entire superglobal array (including $_SESSION) before PHP has finished initializing the session or if the SafeString class isn't declared early enough in the lifecycle.
The root cause lies in how StringsToSafeString interacts with the $_SESSION variable. If this function runs while require_once __WEBROOT__ . '/includes/safestring.class.php'; has not yet been executed, or if the session is already started and PHP attempts to serialize the modified array before the class definition is available in memory, you create incomplete objects. The code snippet provided shows a recursive traversal of superglobals. While require_once is present at the top, the execution flow matters immensely. If this logic runs inside a function that gets called before the autoloader or explicit require has fully resolved the class map for SafeString, serialization will fail.
The most robust solution is to decouple the session start from the sanitization logic. You should ensure that require_once is placed at the very top of your entry file, before any output buffering starts and before session_start() is called. Once the SafeString class is defined, the transformation can proceed safely because the serializer will have access to the class schema.
However, even with the class loaded, modifying $_SESSION directly inside a recursive function that also touches other superglobals like $_POST or $_SERVER can be risky if you are not careful about scope. The __PHP_Incomplete_Class error specifically indicates that the serializer wrote a partial dump. To fix this, ensure that no object instances exist in the session data before the class is defined.
A safer pattern involves initializing the session first, ensuring the environment is clean, and then applying your sanitization logic only to string values within the session array after the SafeString class is fully loaded and available to the serializer.
<?php
// 1. Load the SafeString class FIRST before any session manipulation
require_once __WEBROOT__ . '/includes/safestring.class.php';
// 2. Start the session only after the class is defined
session_start();
// 3. Now it is safe to traverse and transform $_SESSION data
function StringsToSafeString(&$array)
{
foreach ($array as $key => $value) {
// Only target strings to avoid breaking other object types
if (is_string($array[$key])) {
$array[$key] = new SafeString($array[$key]);
} elseif (is_array($array[$key])) {
StringsToSafeString($array[$key]);
}
}
}
// Apply only to the session data now that the class is loaded
StringsToSafeString($_SESSION);
This approach guarantees that when serialize() runs internally within PHP's session handler, it has the necessary blueprint for SafeString. If you must maintain compatibility with older PHP versions or specific serialization configurations, consider using a custom session handler that manually handles the serialization and ensures the class is always registered before writing to the storage backend.
The trade-off here is performance: wrapping every string in an object adds overhead. For high-traffic sites, you might want to weigh whether the XSS protection provided by SafeString outweighs the cost of object instantiation on every request. Alternatively, consider using output encoding or context-aware escaping directly where data is rendered, rather than forcing a wrapper class on every single variable. But if you choose the wrapper approach, strict adherence to the load order is non-negotiable.