6

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..

4

4 回答 4

14

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

于 2012-12-08T04:05:36.310 回答
8

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"
于 2013-10-26T11:40:10.233 回答
2

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

于 2013-07-29T02:41:34.093 回答
2

You could also use stripcslashes if there are no other escape sequences or if you don't mind converting not only hex escape sequences, but also some special characters (such as \0, \a, \b, \f, \n, \r, \t and \v).

But if you'd like to convert only hex sequences, you might use preg_replace_callback to limit what sequences should be changed, like this:

function hex2str($string) {
    return preg_replace_callback(
        '/(\\\\x[a-f\d]{2})+/i', 
        function ($matches) {
            return stripcslashes($matches[0]);
        },
        $string
    );
}
于 2018-08-01T16:15:09.947 回答