Search code examples
phpdecodingiconvrequest.querystring

how to decode string on php. iconv decode is not work


request http://a.com/?q=\xC3\xA2\xB0\xED

source

$str1 = "\xC3\xA2\xB0\xED";
$str2 = '\xC3\xA2\xB0\xED';
$str3 = $_GET['q'];

echo "string1 : " . mb_detect_encoding($str1) . "<br>";
echo iconv("CP949", "UTF-8", $str1) . "<br>";
echo "string2 : " . mb_detect_encoding($str2) . "<br>";
echo iconv("CP949", "UTF-8", $str2) . "<br>";
echo "string3 : " . mb_detect_encoding($str3) . "<br>";
echo iconv("CP949", "UTF-8", $str3) . "<br>";

response

string1 : UTF-8
창고
string2 : ASCII
\xC3\xA2\xB0\xED
string3 : ASCII
\xC3\xA2\xB0\xED

$str2, $str3 decode is fail.. How can i fix it? And Why is it different.. single quote string VS double quote string

Version : PHP 7.1.30

Thanks in advance


Solution

  • When you use single quote for a string each character is as it is and php doesn't interpret it, so $str2 can't convert to another encoding.

    Also Query strings assumes as single quote strings so $str3 is like $str2.

    And the solution is stripcslashes. it actually converts a single quote string to double quote string.

    and you can fix it in this way:

    $str2 = '\xC3\xA2\xB0\xED';
    $str2 = stripcslashes($str2);
    $str3 = $_REQUEST["q"];
    $str3 = stripcslashes($str3);