PHP strlen before unpack
Check a binary record's byte count before using unpack to decode a four-byte value.
A simple example
strlen before unpack
- Start with One available byte
- Do this Try to read a complete two-byte field
- Result One byte is missing
Syntax
strlen($record) === 4
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpRead a stock count from a short record
A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.
<?php
$record = "\x00\x05";
if (strlen($record) !== 4) {
echo 'Request the complete record';
} else {
echo unpack('Ncount', $record)['count'];
}
Request the complete record
The two-byte transfer falls short of the four bytes required for a stock count.
Decode a complete gate count
A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
Detect a cut-off meter record
A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
What to watch for
PHP strings can hold zero bytes. Use strlen to count the transferred bytes even if they are not printable characters.