Sending url and related Chinese garbled code problem solution based on curl and post by PHP

  • 2021-08-21 20:02:10
  • OfStack

In this paper, an example of PHP based on curl post to send url and related Chinese garbled code solution. Share it for your reference, as follows:

This problem has troubled me for several days. The url parameters of the specified website are always garbled in Chinese. The specified website is encoded by utf8, and what I sent is also encoded by utf8. However, it is still garbled. file_get_contents was used at first, then replaced with curl and php_curl was turned on in php. ini, but it still failed. header was added and finally solved. The code is as follows:


$url = 'http://'; // The platform service address of the calling interface 
$post_string = array('a'=>'b');
$ch = curl_init();
$this_header = array(
"content-type: application/x-www-form-urlencoded; 
charset=UTF-8"
);
curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
if($result)
echo "<script>\nalert(\" Synchronization succeeded!  \");\n</script>";
curl_close($ch);

Summary: To solve this kind of coding problem, first of all, we should confirm what the codes in the two places are. Secondly, if the codes are the same, we can send them directly. To use curl, we need to add header to set charset. Finally, we should check and try more. If one method can't work, try another one. If none of them work, we should consider the problem again from scratch, which can always be solved.

PS: content-type is set here to: application/x-www-form-urlencoded; The first article https://www.ofstack.com/article/129039. htm in this site gives a detailed explanation of the principle and setting method of content-type, which is helpful for readers to deepen their understanding.

For more readers interested in PHP related content, please check the topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Operation and Operator Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: