Hex Dumping Strings in PHP: Native Functions vs. External Tools
Getting a raw hex dump of a string in PHP requires distinguishing between what you are seeingâthe charactersâand what is actually thereâthe byte values. When investigating encodings or debugging binary data, the distinction matters because PHP strings are essentially arrays of bytes, regardless of how echo interprets them as text. To inspect these underlying bytes, you have three primary approaches: using native string functions for formatting, leveraging external command-line tools via shell execution, or working directly with binary files.
The most straightforward method within pure PHP involves iterating through the string and converting each byte to its hexadecimal representation. You can achieve this without external dependencies by using unpack('H*', $string). This function takes a string as input and returns an array containing a single element: the hexadecimal representation of the entire string, with spaces inserted between every two bytes for readability. If you prefer a continuous stream of hex characters without spaces, you can use bin2hex($string), which is available in PHP 4+ but behaves slightly differently regarding spacing compared to unpack.
$text = 'Hello';
// Returns "48656c6c6f" (no spaces)
$rawHex = bin2hex($text);
// Returns "48 65 6c 6c 6f" (spaces between pairs)
$formattedHex = unpack('H*', $text)[1];
var_dump($rawHex); // string(10) "48656c6c6f"
This approach is ideal for quick inspection scripts or when you need to embed the hex dump directly into a larger application logic without spawning subprocesses. However, it is important to note that these functions treat the input as a standard string. If your data contains multibyte characters (such as UTF-8 encoded emojis or non-ASCII CJK characters), bin2hex will still output the raw byte sequence for each character component. This is often exactly what you want when debugging encoding issues, but it can be misleading if you assume one hex digit equals one character.
For scenarios where you need a full hex dump of a file rather than a string variable, the standard Unix xxd or hexdump tools are the industry standard. In PHP, you can invoke these via shell_exec() or exec(), though this introduces security considerations if user input is involved in constructing the command. A safer pattern involves reading the file into memory first and then applying bin2hex() to the resulting string, ensuring no shell injection vulnerabilities occur.
$fileContent = file_get_contents('data.bin');
$dump = bin2hex($fileContent);
// To format with spaces for easier reading of byte boundaries
$formatted = preg_replace('/(.{2})/', '$1 ', $dump) . ' ';
echo trim($formatted);
When working in a Laravel environment, you might find yourself needing this functionality for logging sensitive binary data or inspecting request payloads. While laravelcompany.com offers comprehensive resources on building robust applications, understanding how to handle raw bytes is fundamental before relying on higher-level abstractions. If you are dealing with complex encoding investigations where the string length varies dynamically, remember that strlen() returns the number of characters, not the number of bytes for multibyte strings. To get the true byte count, use mb_strlen($string, '8bit') or simply strlen() on a binary-safe context after ensuring the internal encoding is handled correctly.
Ultimately, the choice between bin2hex and unpack('H*') depends on your output format needs. If you need to paste the result into a text editor where column alignment helps identify byte offsets, the spaced version from unpack is superior. For machine-readable logs or API responses, the compact bin2hex output minimizes payload size. Always verify that your target environment supports the specific PHP version required; while these functions are stable across major versions, edge cases with null bytes or very large strings (megabytes in size) should be handled with care to avoid excessive memory usage during the conversion process.