In the world of web development, converting strings to hexadecimal representation is a common task. Whether you're working with database storage, API integrations, cryptography, or debugging binary data, understanding how to convert strings to hexadecimal in PHP is an essential skill. This comprehensive guide will explore various methods, with a special focus on the built‑in bin2hex function, and provide practical examples from different languages and use cases.
Why Convert Strings to Hexadecimal?
Hexadecimal (base‑16) representation is widely used in computing because it provides a compact, human‑readable way to represent binary data. Common scenarios include:
- Storing binary data in text‑based formats (JSON, XML, databases)
- Encoding data for URL parameters
- Representing cryptographic hashes and keys
- Debugging network packets or file contents
- Working with legacy systems that expect hex‑encoded input
PHP offers several functions to perform this conversion, with bin2hex being the most straightforward and commonly used.
The bin2hex Function
The bin2hex function converts a string of binary data into its hexadecimal representation. It returns a string where each byte of the input is represented as two hexadecimal digits.
Syntax:
bin2hex(string $string): string Parameters:
$string– The input string (binary or ASCII/UTF‑8 text).
Return value:
- A hexadecimal string (uppercase letters A‑F).
Example:
$text = "Hello";
$hex = bin2hex($text);
echo $hex; // Output: 48656c6c6f For a deeper dive into the function, refer to the official PHP documentation on bin2hex.
Basic Examples with bin2hex
Let's start with simple ASCII strings:
<?php
$greetings = [
"English" => "Hello",
"Spanish" => "Hola",
"French" => "Bonjour",
"Italian" => "Ciao"
];
foreach ($greetings as $lang => $word) {
echo "$lang: $word -> " . bin2hex($word) . "\n";
}
?> Output:
English: Hello -> 48656c6c6f
Spanish: Hola -> 486f6c61
French: Bonjour -> 426f6e6a6f7572
Italian: Ciao -> 4369616f Handling Multi‑byte Characters (UTF‑8)
When working with non‑English text, strings are often encoded in UTF‑8. bin2hex works directly on the raw bytes of the string, so it correctly handles UTF‑8 encoded characters.
<?php
$international = [
"Japanese" => "こんにちは", // "Hello"
"Russian" => "Привет", // "Hello"
"Arabic" => "مرحبا", // "Hello"
"Hindi" => "नमस्ते" // "Hello"
];
foreach ($international as $lang => $text) {
$hex = bin2hex($text);
echo "$lang: $text -> $hex\n";
}
?> Output (truncated for readability):
Japanese: こんにちは -> e38193e38293e381abe381a1e381af
Russian: Привет -> d0bfd180d0b8d0b2d0b5d182
Arabic: مرحبا -> d985d8b1d8add8a8d8a7
Hindi: नमस्ते -> e0a4aee0a4aee0a4b8e0a4a4e0a587 Notice that each Unicode character expands to multiple bytes (e.g., こ is e3 81 93 in UTF‑8), so the resulting hex string length is twice the number of bytes.
Converting Hexadecimal Back to String
To reverse the process, PHP provides the hex2bin function, which converts a hexadecimal string back to its original binary representation.
<?php
$original = "München"; // German city name
$hex = bin2hex($original);
echo "Hex: $hex\n";
$restored = hex2bin($hex);
echo "Restored: $restored\n";
?> Output:
Hex: 4dc3bcnchen
Restored: München Note: The example above may look odd because bin2hex outputs lowercase hex digits, and the German umlaut ü is represented as two bytes (c3 bc) in UTF‑8. When printing, ensure your terminal/script supports UTF‑8 to see the correct characters.
Alternative Methods for String to Hex Conversion
While bin2hex is the simplest, there are other ways to achieve the same result, each with its own use cases.
1. Using unpack()
The unpack() function with the H* format specifier can also convert a string to hex:
<?php
$text = "Köln";
$hex = unpack("H*", $text)[1];
echo $hex; // Output: 4bc3b86c6e
?> This method returns the same result as bin2hex.
2. Manual Conversion with ord() and dechex()
For educational purposes or when you need fine‑grained control, you can loop through each character:
<?php
function stringToHexManual($str) {
$hex = '';
for ($i = 0; $i < strlen($str); $i++) {
$hex .= dechex(ord($str[$i]));
}
return $hex;
}
$text = "Wien";
echo stringToHexManual($text); // Output: 5769656e
?> Caution: This method works for single‑byte encodings (like ASCII or ISO‑8859‑1) but will fail for multi‑byte UTF‑8 because ord() only reads the first byte of a multi‑byte character. For UTF‑8, always use bin2hex or unpack.
3. Using sprintf() with Formatting
You can combine sprintf() with ord() to produce zero‑padded hex digits:
<?php
$text = "Århus";
$hex = '';
for ($i = 0; $i < strlen($text); $i++) {
$hex .= sprintf("%02x", ord($text[$i]));
}
echo $hex; // Output: c38572687573
?> Again, this suffers from the same limitation with multi‑byte characters.
Practical Applications
1. Storing Binary Data in Databases
When storing binary data (e.g., file contents, encrypted strings) in a text column, hex encoding is a safe choice:
<?php
// Simulate a file upload
$fileContent = file_get_contents('image.jpg');
$hexEncoded = bin2hex($fileContent);
// Store $hexEncoded in your database (e.g., TEXT column)
// Later, retrieve and decode
$retrievedHex = $hexEncoded; // from DB
$originalData = hex2bin($retrievedHex);
file_put_contents('restored_image.jpg', $originalData);
?> 2. URL‑Safe Encoding
Hexadecimal strings are URL‑safe because they contain only digits and letters A‑F. This makes them ideal for passing binary data in URLs without percent‑encoding.
<?php
$binaryData = "user:secret";
$hex = bin2hex($binaryData);
$url = "https://example.com/api?token=$hex";
// On the receiving side
$receivedHex = $_GET['token'];
$decoded = hex2bin($receivedHex);
// Use $decoded
?> 3. Debugging and Logging
When debugging binary protocols or examining raw data, hex output is much more readable than unprintable characters.
<?php
$binaryPacket = "\x01\x02\x03\xFF\x00";
error_log("Received packet: " . bin2hex($binaryPacket));
// Log entry: Received packet: 010203ff00
?> Performance Considerations
bin2hex is implemented in C and is highly optimized. For most use cases, it is the fastest option. When dealing with very large strings (megabytes or more), bin2hex remains efficient because it operates on the raw memory without additional overhead.
Manual loops in PHP can be significantly slower, especially for large inputs. Always prefer bin2hex when performance matters.
Handling Edge Cases
Empty String
<?php
$empty = "";
$hex = bin2hex($empty); // Returns an empty string
?> Invalid Hexadecimal Input for hex2bin
When using hex2bin, ensure the input string has an even length and contains only valid hex characters (0‑9, A‑F, a‑f). Otherwise, it will trigger a warning and return false.
<?php
$invalid = "4G";
$result = hex2bin($invalid); // false, and a warning is issued
?> Case Sensitivity
bin2hex always returns lowercase hex digits. If you need uppercase, you can use strtoupper():
<?php
$hex = bin2hex("hello");
echo strtoupper($hex); // 68656C6C6F
?> Conclusion
Converting strings to hexadecimal in PHP is a fundamental operation that can be accomplished easily with the bin2hex function. It handles any binary data, including UTF‑8 encoded text, and is both fast and reliable. For the reverse operation, hex2bin provides a straightforward way to decode hexadecimal back to the original string.
In this guide, we've explored:
- The syntax and usage of
bin2hex - Examples with multiple languages and character sets
- Alternative conversion methods (unpack, manual loops)
- Real‑world applications like database storage and URL encoding
- Performance and edge case considerations
Whether you're building a cryptographic system, a binary data logger, or simply need to debug raw data, PHP's hex conversion functions will serve you well.
For further reading, check out the official documentation: