PHP Fsockopen post JSON data

Source: Internet
Author: User
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.

 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.