How to repair a serialized string which has been corrupted by an incorrect byte count length?

How to repair a serialized string which has been corrupted by an incorrect byte count length?

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

How to repair a serialized string which has been corrupted by an incorrect byte count length?

PHP's serialize() function is powerful, but it expects strict adherence to its format. When you encounter an unserialize() [function.unserialize]: Error at offset warning in production, the issue usually stems from a mismatch between the declared data structure and the actual bytes stored on disk. This often happens when a string is truncated during insertion—perhaps due to character set issues or database row limits—and the serialized header remains intact while the payload is chopped off.

In the specific case provided by the Hotaru CMS error, the tempdata_value column contains a valid serialized structure for the first 10 variables, but the final element, image, is malformed:
s:5:"image";s:19:"C:fakepath100.jpg"}

The declaration says the value is a string of length 19. However, if that file path was too long or contained special characters not properly escaped during serialization, or if the database row limit cut it short, the internal pointer in unserialize() will run out of memory when trying to read the expected number of bytes for the subsequent keys (or end-of-file markers).

Diagnosing the Corruption

Before attempting a repair, you must verify that the data is indeed corrupted and not just incomplete. You can inspect the raw value using PHP's strlen() against the declared length in the serialized string.

$data = $submitted_data; // The raw value from the database
$lengths = [];

// Regex to find all 's:length:"value'" patterns
preg_match_all('/s:(\d+):"([^"]*)"/', $data, $matches);

foreach ($matches[0] as $pattern) {
    preg_match('/s:(\d+):/i', $pattern, $lenMatches);
    if (!empty($lenMatches)) {
        $declaredLen = (int)$lenMatches[1];
        $actualLen = strlen(substr($pattern, 2)); // Length of the string literal part
        // Note: This is a rough check; for exact repair, we need to parse the structure.
    }
}

A more robust check involves parsing the serialized array manually to find where the byte count mismatch occurs. You can iterate through the string, tracking your current offset. If you encounter an s: declaration followed by a number that exceeds the remaining bytes in the string until the next type indicator (like ; or end of string), you have found the corruption point.

Repairing the Serialized String

Once identified, the repair strategy depends on whether you can reconstruct the original value or if you must truncate and re-serialize. Since image paths are often dynamic, truncation is risky. However, in many CMS scenarios, the safest immediate fix is to identify the last valid key-value pair and drop everything after it, effectively removing the corrupted entry from the array structure.

Here is a function that attempts to repair the string by iterating through it and stopping before an invalid length declaration:

function repairSerializedString($corruptedData) {
    if (!$corruptedData) return null;

    $offset = 0;
    $length = strlen($corruptedData);
    $type = '';
    $key = '';
    $value = '';
    
    // We will build a new string based on valid chunks
    $repairBuffer = '';

    while ($offset < $length) {
        // Determine the current type at this offset
        if (isset($corruptedData[$offset]) && $corruptedData[$offset] === 's') {
            // String type: s:length:"content";
            $type = 'string';
            $pattern = '/s:(\d+):"([^"]*)"/';
            
            // Find the start of the next potential string or end
            if (preg_match($pattern, substr($corruptedData, $offset), $matches)) {
                $declaredLen = (int)$matches[1];
                $content = $matches[2];
                
                // Calculate actual length available in this segment
                // We need to ensure we don't cross into the next field
                $segmentStart = $offset;
                $segmentEnd = strpos($corruptedData, ';', $offset);
                if ($segmentEnd === false) $segmentEnd = $length;

                $actualBytesAvailable = $segmentEnd - $segmentStart;
                
                // If declared length does not match available bytes (accounting for quotes and semicolon)
                // Or if the content itself looks truncated (e.g., "C:fakepath100.jpg" is incomplete)
                if ($declaredLen > strlen($content)) {
                    // Corruption detected at this specific string. 
                    // Strategy: Truncate the array to remove this invalid key entirely.
                    // We must find the start of the NEXT type indicator (like 's:', 'i:', 'b:') after this failed block.
                    
                    $nextFieldStart = strpos($corruptedData, ':', $segmentEnd);
                    
                    if ($nextFieldStart !== false) {
                        // Found the next field, so we can safely cut here.
                        // However, to repair, we might just want to ignore this entry or set it to null.
                        // For a full array fix, we reconstruct up to this point and stop.
                    }
                }
                
                $repairBuffer .= 's:' . strlen($content) . '":"' . $content . '";';
                $offset = $segmentEnd + 1; // Move past the closing semicolon
            } else {
                // Could be a different type or malformed header. Stop parsing.
                break;
            }
        } elseif (isset($corruptedData[$offset]) && $corruptedData[$offset] === 'i') {
            // Integer: i:value;
            $type = 'integer';
            if (preg_match('/i(-?\d+);/', substr($corruptedData, $offset), $matches)) {
                $repairBuffer .= 'i:' . $matches[1] . ';';
                $offset += strlen($matches[0]);
            } else {
                // Corrupted integer or text where int expected. Stop.
                break;
            }
        } elseif (isset($corruptedData[$offset]) && $corruptedData[$offset] === 'b') {
            // Boolean: b:value;
            if ($corruptedData[$offset + 1] === '0' || $corruptedData[$offset + 1] === '1') {
                $val = (int)$corruptedData[$offset + 1];
                $repairBuffer .= 'b:' . ($val ? '1' : '0') . ';';
                $offset += 3; // b:0; or b:1;
            } else {
                 // Corrupted boolean. Stop.
                 break;
            }
        } elseif (isset($corruptedData[$offset]) && $corruptedData[$offset] === 'a') {
             // Array: a:length:{...};
             if ($offset + 1 < $length) {
                $repairBuffer .= substr($corruptedData, $offset, 2); // "a:"
                $offset += 2;
             } else {
                break;
             }
        } else {
            // Unknown character or end of stream. Stop.
            break;
        }
    }

    return $repairBuffer ?: null;
}

Preventing Future Corruption

The root cause here is likely the saveSubmitData method inserting data directly into a column without validating length constraints or handling encoding issues gracefully. If the database table TABLE_TEMPDATA has a fixed length column (e.g., VARCHAR(255)), and you attempt to save a serialized string that exceeds this limit, MySQL will silently truncate the value. When unserialize() reads it back, it sees the header claiming a 19-character string but only finds fewer bytes, causing the crash.

To prevent this:

  1. Use Dynamic Columns: Ensure the column storing tempdata_value is TEXT or LONGTEXT, not a fixed-length VARCHAR. This gives you enough room for large serialized arrays without truncation.
  2. Validate Before Insert: Check strlen(serialize($vars['submitted_data'])) before running the insert query. If it exceeds the column limit, truncate the array of variables rather than saving incomplete data.
  3. Sanitize Paths: Ensure image paths like C:fakepath100.jpg are URL-encoded or properly escaped if they contain colons or special characters that might interfere with serialization parsing in certain contexts.

By addressing the column size constraints and validating the serialized length before insertion, you eliminate the possibility of partial writes that lead to unserialize() errors.

Our network