Is there a native PHP function to convert a string into its hexadecimal representation?

Solution 1: Evaluating PHP Code from Hex Strings

Although PHP has no native function to directly run hex-encoded code, you can use hex2bin() combined with eval() to execute it:


// Example 1: Direct hex string
eval(hex2bin("6563686f20706928293b")); // Output: 3.14159265359

// Example 2: Convert regular PHP code to hex, then back
eval(hex2bin(bin2hex("echo pi();"))); // Output: 3.14159265359

Calling a function whose name is in hex:


$ echo '<? $_=hex2bin(7069); die($_());' | php

Here, 7069 is the hex representation of “pi”.

This will output:


3.14159265359

Notes:

hex2bin() converts hex strings to their binary representation.

eval() executes the resulting PHP code.

Be cautious: using eval() can be dangerous if the input is not trusted.

Solution 2: Converting a String to Hex Escapes (\xHH)

Although PHP has no built-in function for this, you can achieve it in one line using bin2hex() and str_split():


$str = 'ABC';
$str = '\x' . implode('\x', str_split(bin2hex($str), 2));
echo $str; // Output: \x41\x42\x43

Alternative approach using PHP documentation method:


$str = 'ABC';
$field = bin2hex($str);
$field = chunk_split($field, 2, "\\x");
$field = "\\x" . substr($field, 0, -2);
echo $field; // Output: \x41\x42\x43