Current Location: Home> Latest Articles> How to Solve the Chinese Garbled Characters Issue in PHP URL Parameters

How to Solve the Chinese Garbled Characters Issue in PHP URL Parameters

gitbox 2025-06-28

I. Problem Definition

In PHP programming, it is common to pass Chinese characters through URL parameters. However, since Chinese characters occupy more bytes than English characters, this often results in garbled text. To fix this issue, a specific encoding conversion for Chinese characters is required.

II. Solutions

URL Encoding and Decoding

URL encoding converts special characters in a URL into a format that complies with URL standards. In PHP, you can use the urlencode() function to encode strings, ensuring all non-alphanumeric characters are replaced with the %XX format, where XX represents the character’s ASCII code in hexadecimal.

For example, to URL encode the string “中文”, you can use the following code:

$encoded_str = urlencode('中文');
 echo $encoded_str; // %E4%B8%AD%E6%96%87

The code above converts “中文” into “%E4%B8%AD%E6%96%87”. To decode an encoded string, you can use the urldecode() function. For example:

$decoded_str = urldecode('%E4%B8%AD%E6%96%87');
 echo $decoded_str; // 中文

Additionally, the http_build_query() function can convert an array into URL parameters. If there are multiple key-value pairs, you can combine them into a complete URL:

$data = array('name' => '中文', 'age' => 18);
$query_string = http_build_query($data);
 echo $query_string; // name=%E4%B8%AD%E6%96%87&age=18

Modify PHP’s Default Encoding

If your PHP application frequently uses Chinese characters, you can avoid garbled text by changing PHP’s default encoding. Use the header() function at the top of your PHP file to set the character encoding, for example:

<span class="fun">header('Content-type:text/html;charset=utf-8');</span>

With this setting, all output will use UTF-8 encoding, ensuring that passing Chinese characters in URL parameters won’t cause garbled text.

Ensure Encoding Settings in PHP.ini Are Correct

It’s also important to make sure the following three parameters in your PHP.ini file are configured correctly:

default_charset = &#039;UTF-8&#039;
 mbstring.internal_encoding = &#039;UTF-8&#039;
 mbstring.http_input = &#039;UTF-8&#039;

These parameters control default encoding, internal encoding, and HTTP input encoding. Proper configuration can effectively prevent issues with Chinese garbled characters.

III. Conclusion

When working with PHP, handling Chinese characters in URL parameters is crucial. By using URL encoding and decoding, modifying PHP’s default encoding, and ensuring correct PHP.ini settings, you can effectively avoid garbled text. Mastering these methods will ensure that your PHP applications can properly process URLs containing Chinese characters.