Can php fsockopen post json data? If you know, please leave the code, thanks here!
Reply content:
Can php fsockopen post json data? If you know, please leave the code, thanks here!
Because it is not clear how you want to submit the json data, the following two situations are shown as examples.
The first case: The entire data submitted is the content in JSON format.
1.php
'hello','b'=>'world','c'=>'Chinese characters');
$data = json_encode($post_fields);//Convert to a string in JSON format
$data = array(
'POST /123.php HTTP/1.0',//The requested address
'Host: localhost',
'Content-type: application/x-www-form-urlencoded',
'Content-length:'. strlen($data),//fill data length
'',//The separator between request header and data
$data//fill data body
);
//Note to modify the domain name and port number
$sock = fsockopen("localhost", 800, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno) ");
fwrite($sock, implode("\r\n", $data));
$data ='';
while(!feof($sock)){//Test whether the file pointer reaches the end of the file
$data .= fgets($sock,1024);
}
fclose($sock);
echo $data;
The code of the corresponding 123.php file is as follows:
The results after code execution are as follows:
HTTP/1.1 200 OK
Date: Mon, 21 Sep 2015 06:34:12 GMT
Server: Apache/2.4.12 (Win32) PHP/5.6.9
X-Powered-By: PHP/5.6.9
Content-Length: 118
Connection: close
Content-Type: text/html; charset=UTF-8
object(stdClass)#1 (3) {
["a"]=>
string(5) "hello"
["b"]=>
string(5) "world"
["c"]=>
string(6) "Chinese characters"
}
The second case: JSON format data is submitted as data.
Make the following changes based on the above code:
1.php
$data ='xyz=' .json_encode($post_fields);//Converted to a string in JSON format
The execution result is the same as before.