Recently made PHP WebService server, found in the Get method to get parameters when the parameters are garbled. A toss-up after discovering the local language problem in the browser.
First look at the simple test code:
- <? PHP
- Header ("Content-type:text/html;charset=utf-8");
- $name = $_GET [' name '];
- var_dump ($name);
- ?>
The test results are as follows:
The code declares that the response content is encoded as utf-8, and the contents of the display are really garbled. Note here that the length of the Var_dump variable is only 4, and it is clear that the length of the two characters in the Utf-8 encoding is definitely more than 4 bytes, and then we'll look at the URL of Firefox's access page.
Firefox will automatically encode the Chinese URL, so we can see that the test has become%b2%e2%ca%d4, it is clear that here a word is two bytes, is the gb2313, GBK and other Chinese encoding format, rather than UTF-8 encoding. If we switch the encoding of the page to GBK, the Chinese parameter will be displayed as normal, see
Next we do another test, the code is as follows:
- <?php
- Header ("Content-type:text/html;charset=utf-8");
- $name = $_GET [' name '];
- var_dump ($name);
- ?>
-
- <form method= "GET" >
- <input name= "Name" />
- <input type= "Submit" value= "Input Chinese submission" />
- </form>
Test results, normal display:
So what is causing the problem to happen?
The answer is that the browser default encoding in the mischief, we all use the Chinese system, the browser default encoding will naturally be set to localization, such as my own computer, IE and Firefox default encoding is GB series.
When the browser asks the user to enter a URL, it will default to send the Chinese in the URL in the default encoding format instead of the page's encoded format, which is why the link with Chinese in the page is normal and we enter the link manually
The reason why it will be garbled. Similarly, if we adjust the default encoding of the browser to Utf-8, then the Chinese in the input URL will be encoded according to Utf-8.
In addition to the above, this situation can occur in the following situations:
If the address of the GBK encoded page is linked to the Utf-8 page, the Chinese of the GBK page is routed to the next page according to the GBK format encoding, then the UTF-8 encoding will definitely appear garbled after receiving it.
IIS URL rewrite module, the rewritten Chinese encoding is also GBK, if your page is UTF-8 encoded, then the override parameter will be invalidated. In these cases, we need to use PHP's built-in transcoding function to handle the encoding problem:
Scenario 1:
- $name = iconv("GBK","Utf-8",$name );
Scenario 2:
- mb_convert_encoding($name, "Utf-8", "GBK" );
PHP received get method passed in Chinese parameter garbled problem