In PHP, the pack() function is a powerful binary data packaging tool, which is often used to generate binary data transmitted by the network, file format analysis and other scenarios. It converts data into binary strings based on the specified format string. However, many developers often encounter the problem of "inconsistent data length leads to abnormal behavior". This article will analyze the causes in detail and teach you how to troubleshoot them.
The pack() function accepts two parameters:
string pack(string $format, mixed $values, mixed ...$values)
$format : format string, defines the type and length of the data, such as a4 represents a 4-byte string, N represents a 32-bit unsigned big-endian integer, etc.
$values : input data in the corresponding format.
It returns a binary string that packages the data in format.
Suppose you use a4 (fixed 4-byte string) format to package a string with less than 4 lengths, PHP will automatically fill it with empty bytes, which is usually the expected behavior.
However, if the format does not match the data, or the length of the number type is incorrect, it may cause:
The output data is abnormal, resulting in subsequent parsing failure.
There is an error in the network protocol and communication cannot be done normally.
The file format is wrong, the file is corrupted.
For example:
<?php
// expect4Byte string,But only3byte
echo bin2hex(pack('a4', 'abc')); // 61626300,Finished at the end0byte
// expect4byte整数,But passing in strings will cause exception
echo bin2hex(pack('N', 'abc')); // An error will be reported or unpredictable data will be generated
?>
Pack() 's format string is very sensitive to type. Number type formats (such as N , L ) require integer data, and string formats (such as a , A ) require strings.
<?php
$int = 1234;
$str = "hello";
// Correct usage
$data = pack('N', $int);
// Wrong usage(Will cause exceptions)
$data = pack('N', $str);
?>
For fixed-length string formats, such as a4 and A8 , confirm whether the string length is sufficient or too long.
A will fill in empty bytes when the format is insufficient
A will fill in spaces when the format A is insufficient
It will be cut off too long
<?php
echo bin2hex(pack('a4', 'abcde')); // 61626364,Excess part is truncated
echo bin2hex(pack('A4', 'ab')); // 61622020,Make up spaces later
?>
Use the bin2hex() function to view the hexadecimal representation of the binary data returned by pack() to facilitate analysis of whether it meets expectations.
<?php
$data = pack('a4N', 'abc', 1234);
echo bin2hex($data);
?>
pack() supports multiple format characters and corresponding multiple values, and the order must be matched.
<?php
// The format string has2Format characters,Must pass2Parameters
$data = pack('a4N', 'test', 100);
?>
If the number of parameters does not match, the result may be incorrect.
The official manual and community tutorial are very helpful. Here is the sample code access address: