PostgreSQL text types cannot store the zero byte represented by \0. Validate text before binding it so a PHP database driver cannot silently shorten the value or send data that PostgreSQL rejects. If zero bytes are legitimate, model the column as binary data instead.
Last updated: October 10, 2026.
<?php
declare(strict_types=1);
function requirePostgresText(string $value): string
{
if (str_contains($value, "\0")) {
throw new InvalidArgumentException('Text contains a NUL byte.');
}
return $value;
}
$statement = $pdo->prepare(
'INSERT INTO notes (body) VALUES (:body)'
);
$statement->execute([
'body' => requirePostgresText($submittedBody),
]);Validate the decoded value immediately before persistence, not only in the browser. Log a safe identifier and the validation outcome, but do not log the rejected content when it may contain credentials or private data.
Why PostgreSQL rejects code zero
PostgreSQL supports UTF-8 text, but its character-type documentation explicitly excludes character code zero. A NUL can enter PHP through an uploaded file, a decoded protocol field, copied binary content, or an unexpected transformation. Searching with str_contains($value, "\0") is a direct validation rule for PHP 8 and later.
Do not remove every zero byte automatically. Deleting it changes the submitted value and can hide an upstream parsing error. Reject the request with a clear validation message, then inspect why a supposedly textual field contains binary content.
Use bytea for intentional binary values
If the field represents a hash digest, encrypted payload, compressed content, or arbitrary file bytes, use PostgreSQL bytea rather than text. The PostgreSQL binary data documentation defines bytea for raw bytes, including zero values. Bind binary streams using the behavior supported by your PDO driver and test round trips with representative values.
Keep textual and binary columns separate so validation and output encoding remain predictable. For related database work, see connecting PHP to a database, PostgreSQL composite conditions, and secure PHP form processing.