PHP convert string to hex and hex to string

To convert a string to its hexadecimal representation, you can use the bin2hex function in PHP. This function takes a string as input and returns a hexadecimal string.

Here's an example of how to use bin2hex:

<?php

$string = 'Hello, World!';
$hex = bin2hex($string);
echo $hex; // 48656c6c6f2c20576f726c6421

To convert a hexadecimal string back to its original string representation, you can use the hex2bin function. This function takes a hexadecimal string as input and returns the original string.

Here's an example of how to use hex2bin:

<?php

$hex = '48656c6c6f2c20576f726c6421';
$string = hex2bin($hex);
echo $string; // Hello, World!

Note that the hex2bin function was introduced in PHP 5.4. If you are using an earlier version of PHP, you can use the pack function with the H* format string to achieve the same result:

<?php

$hex = '48656c6c6f2c20576f726c6421';
$string = pack('H*', $hex);
echo $string; // Hello, World!