Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Hex Code into readable string in PHP

Tags:

string

php

hex

Hi StackOverflow Community,

Here is my question, how to convert php that has hex code into readable string ? On what I mean is all inside this 2 php code..

<?php

echo "\x74\150\x69\163\x20\151\x73\40\x74\145\x73\164\x69\156\x67\40\x6f\156\x6c\171";

echo test['\x74\171\x70\145'];

echo range("\x61","\x7a");

?>

this is un-readable code, I need some php function that can convert those unreadable code into readable code..so it will become like this after convert..

<?php

echo "this is testing only";

echo test['type'];

echo range("a","z");

?>

I know i can just echo that hex to change it to readable string, but I have huge php file and lot's of php file that same like this, so I need php function that can automatically convert them all into readable code.

Thank..

like image 679
Mohd Shahril Avatar asked Dec 08 '12 03:12

Mohd Shahril


3 Answers

It seems your code is obfuscated not only with hex escape sequences, but with octal as well. I've written this function to decode it for you:

function decode_code($code){
    return preg_replace_callback(
        "@\\\(x)?([0-9a-f]{2,3})@",
        function($m){
            return chr($m[1]?hexdec($m[2]):octdec($m[2]));
        },
        $code
    );
}

See it in action here: http://codepad.viper-7.com/NjiL84

like image 162
Sean Johnson Avatar answered Oct 16 '22 08:10

Sean Johnson


I had mixed content where besides hex and oct there was also normal chars.

So to update Sean's code above I added following

function decode_code($code)
{
    return preg_replace_callback('@\\\(x)?([0-9a-f]{2,3})@',
        function ($m) {
            if ($m[1]) {
                $hex = substr($m[2], 0, 2);
                $unhex = chr(hexdec($hex));
                if (strlen($m[2]) > 2) {
                    $unhex .= substr($m[2], 2);
                }
                return $unhex;
            } else {
                return chr(octdec($m[2]));
            }
        }, $code);
}

Example string

"\152\163\x6f\x6e\137d\x65\143\157\x64e"

Decoded output

"json_decode"
like image 21
Elvin Risti Avatar answered Oct 16 '22 09:10

Elvin Risti


You can use PHP's native urldecode() function to achieve this. Just pass the hex encoded string to the function and the output will be a string in readable format.

Here is a sample code to demonstrate:

<?php

echo urldecode("\x74\150\x69\163\x20\151\x73\40\x74\145\x73\164\x69\156\x67\40\x6f\156\x6c\171");

?>

This should output: this is testing only

-- seekers01

like image 27
seekers01 Avatar answered Oct 16 '22 07:10

seekers01