PHP string to hex and hex to string functions

Written by on November 4, 2008 in General - 19 Comments

In my opinion SQL injection is an major issue when it comes to web application development. Typically programmers deal with it by escaping strings, while this is probably the best way to get it handled i want to show you different yet effective approach to this problem – converting string to hex value.

Hex value consists of digits and letters from A to F, so this are “normal” chars which can be inserted safely into query, furthermore you can convert any string into hex value. It doesn’t matter what encoding you are going to use, or what kind of text you are converting (plain text, html, xml, etc).

Converting string to hex

Without any further ado here is a script for converting string into HEX. Actually i should credit someone for this code because i am not the one who wrote it in the first place but unfortunately i do not remember where i found it.

function strToHex($string)
{
    $hex='';
    for ($i=0; $i < strlen($string); $i++)
    {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

Converting string to hex

Now converting backwards – hex to string.

function hexToStr($hex)
{
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2)
    {
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

Well it all looks good and wonderful, but as always there are no roses without torns. First of all string converted to hex value is twice as long as original string. Second if you are going to use hex data in database then handling data may become a bit complicated.

About the Author

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

19 Comments on "PHP string to hex and hex to string functions"

  1. kitt November 11, 2008 at 10:00 am ·

    i have checked it’s really great

  2. asusl February 9, 2009 at 8:11 pm ·


    Second if you are going to use hex data in database then handling data may become a bit complicated.

    — Thanks for this. Very important.

  3. Paul Gregg February 22, 2009 at 8:31 pm ·

    Looping character by character is not the most optimal method for performing this function. Thankfully php already provides the unpack/pack functions which does this in a single step:

    http://pgregg.com/projects/php/code/hexstr.php

  4. Sergiu Popovici June 17, 2009 at 9:30 am ·

    Actually, this is not 100% working. It omits the “0″ before the numbers < 0×10. You will get lots of 0xA, 0xB etc instead of 0x0A or 0x0B. I have put myself a condition and now it really works great.

  5. Greg June 17, 2009 at 8:42 pm ·

    Thanks for sharing Sergiu, i knew there was something wrong but i couldn’t figure it out :)

  6. Eric September 3, 2009 at 2:42 pm ·

    Thanks for the script. I found a little problem with your post, you put “Converting string to hex” on the section of hex to string.

  7. Nate Williams September 17, 2009 at 6:47 pm ·

    Looks awesome.

    Did you update the script above with Sergui’s suggestion?

  8. Martin November 15, 2009 at 3:46 pm ·

    I fixed the strToHex so that it will add “0″ when required. Also it will do un UpperCase.

    Regards,
    and Tks for your help.

    function strToHex($string)
    {
    //return bin2hex($string);
    $hex=”;
    for ($i=0; $i < strlen($string); $i++)
    {
    if (ord($string[$i])<16)
    $hex .= "0";
    $hex .= dechex(ord($string[$i]));
    }
    return strtoupper($hex);
    }

  9. joan December 18, 2009 at 9:39 am ·

    hi,
    how can i get the string value for this hex value: 0x0C?

    the expected output is: \f

    this returns empty:
    chr(hexdec(’0x0C’));

    any idea how to get more than one char value from hex?

  10. phpnewbie January 12, 2010 at 12:37 pm ·

    62E 635 645 20 35 30 30 2E 30 30 30 20 4B 57 44 20 645 646 20 62D 633 627 628 20 32 35 38 38 627 644 645 62A 628 642 64A 20 31 2C 34 32 31 2E 36 31 32 20 4B 57 44 20 627 644 645 62A 648 641 631 20 31 2C 34 32 31 2E 36 31 32 20 4B 57 44

    this function does nt work with this..!!

  11. sun0x0001 February 11, 2010 at 6:57 pm ·

    Yo! Thanks for hexToStr() func!
    Suppose alternative might be usefull for smb:

    $s = preg_replace(‘#(\w)(\w)#e’, “chr(hexdec(‘$1$2′))”, $hex);

  12. cvk June 11, 2010 at 2:25 pm ·

    strToHex doesn’t work as expected. Try this instead:

    function strToHex($string)
    {
    $hex=”;
    for ($i=0; $i < strlen($string); $i++)
    {
    $hex .= sprintf("%02x",ord($string[$i]));
    }
    return $hex;
    }

  13. ThA-B September 9, 2010 at 10:22 am ·

    Hi, unfortunately (or fortunately) i must agree to Paul Gregg. Looping large strings (for example files to be handled in sql inserts) 5Mb file convertion on my server is at ~5 seconds. If you add check for 0×0 => 0×00 then it becomes ~ 8seconds when using unpack(‘H*’) takes 1.5seconds.

    On the other hand using looping gives additional control over process so thanks for this too.

  14. arundhuti March 3, 2011 at 11:20 am ·

    Thanks for sharing.it really helps for the beginers.Can you let me how can i generate hex code for chinesse language and shown in front-end?

  15. yippy March 19, 2011 at 3:41 pm ·

    base64 anyone? :D

  16. Komb July 7, 2011 at 10:10 am ·

    If you need to convert string to hex, just use built-in function:

    bin2hex($string)

    For reverse conversion native hex2bin() is in manual, but not yet implemented :(

    I use sun0x0001 method – nice and short. Tested on urls.

  17. Shawn July 22, 2011 at 10:20 pm ·

    Hey, I am attempting to carve raw dumps of data for input with a PHP script. I am doing this for fun. Perhaps you could assist me? My problem is outlined here,

    http://stackoverflow.com/questions/6740268/test-php-carve-for-jpg-files

    I used your strhex functions and they work great!

    Just need to figure out why my script is ignoring those zeros :(

    Thanks so much! Send me an e-mail please! e.x.c.a.b.u.s.@.g.m.a.i.l DAWT CAWM

  18. Krrish September 12, 2011 at 12:24 pm ·

    Never thought this way… escaping string is much easier.
    Bookmarked it for future reference…

  19. Alexis April 2, 2012 at 5:05 am ·

    Great couple of functions Greg, and nice fix Sergiu. Thanks

Leave a Comment