PHP hex2bin() Function – Complete Guide with Examples
What is hex2bin()
in PHP?
The hex2bin()
function in PHP is used to convert a hexadecimal string into binary data.
🔹 Use case: It’s commonly used in cryptography, encoding, and working with raw binary data.
🔹 Syntax:
string hex2bin(string $hex_string)
- $hex_string → A hexadecimal string (must contain an even number of characters).
- Returns: The corresponding binary data.
💡 Note: If the input contains non-hex characters or has an odd length, hex2bin()
returns false
.
1. Basic Example of hex2bin()
Let’s convert a hexadecimal string to binary:
<?php
$hex = "48656c6c6f20504850"; // Hex representation of "Hello PHP"
$binary = hex2bin($hex);
echo $binary;
?>
✅ Output:
Hello PHP
🔹 The hexadecimal string 48656c6c6f20504850
represents "Hello PHP"
in ASCII.
2. Using hex2bin() for Encoding & Decoding
A. Encoding to Hex & Decoding Back
We can use bin2hex()
to encode binary data to hex and hex2bin()
to decode it back.
<?php
$text = "PHP is awesome!";
$hex = bin2hex($text); // Convert to Hex
$binary = hex2bin($hex); // Convert back to Binary
echo "Hex: " . $hex . "<br>";
echo "Binary: " . $binary;
?>
✅ Output:
Hex: 50485020697320617765736f6d6521 Binary: PHP is awesome!
📌 Why use this?
- Helps in secure encoding (e.g., storing binary data in a database).
- Useful in cryptographic operations like hashing and encryption.
3. Handling Invalid Hexadecimal Strings
🚨 hex2bin()
only works with valid hexadecimal strings. If you pass an odd-length or non-hex string, it returns false
.
<?php
$invalid_hex = "123"; // Odd-length string
$result = hex2bin($invalid_hex);
if ($result === false) {
echo "Invalid hexadecimal string!";
}
?>
✅ Output:
Invalid hexadecimal string!
✔️ Always validate input before passing it to hex2bin()
to avoid unexpected errors.
4. Practical Uses of hex2bin()
A. Storing Binary Data in a Database
When working with databases, you may need to store binary data as hex strings for compatibility.
Saving Data:
<?php
$data = "Secret Data";
$hex_data = bin2hex($data);
// Store $hex_data in the database
?>
Retrieving Data:
<?php
// Retrieve $hex_data from the database
$binary_data = hex2bin($hex_data);
echo $binary_data; // Outputs: Secret Data
?>
B. Decrypting Encrypted Data
When handling encrypted messages, hex2bin()
helps in converting hex-encoded ciphertext back to its original binary format before decryption.
Example using AES encryption:
<?php
$key = "1234567890abcdef";
$plaintext = "Hello, Secure World!";
// Encrypt and convert to Hex
$encrypted = openssl_encrypt($plaintext, "AES-128-ECB", $key);
$hex_encrypted = bin2hex($encrypted);
echo "Hex Encrypted: " . $hex_encrypted . "<br>";
// Convert Hex back to Binary and Decrypt
$binary_encrypted = hex2bin($hex_encrypted);
$decrypted = openssl_decrypt($binary_encrypted, "AES-128-ECB", $key);
echo "Decrypted: " . $decrypted;
?>
✅ Output:
Hex Encrypted: 6e41b3c7e08f5a... Decrypted: Hello, Secure World!
5. Security Considerations
✔️ Validate Input:
Use ctype_xdigit() to check if a string contains only hex characters:
<?php
$hex_string = "4a6f686e";
if (ctype_xdigit($hex_string)) {
echo "Valid Hex!";
} else {
echo "Invalid Hex!";
}
?>
✔️ Use Try-Catch for Error Handling:
<?php
try {
$result = hex2bin("xyz123");
if ($result === false) {
throw new Exception("Invalid hexadecimal string.");
}
echo $result;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
When to Use hex2bin()
📌 Use hex2bin()
when:
✅ Converting hexadecimal strings back to binary format
✅ Decoding binary-encoded database values
✅ Handling cryptographic functions
✅ Working with binary file data
⚠️ Remember:
❌ Input must have an even number of hex characters
❌ If invalid, hex2bin()
returns false