php fsockopen post json数据

WBOY
Release: 2016-06-06 20:27:51
Original
2283 people have browsed it

php fsockopen 可以 post json数据吗? 知道的请留下代码,在此谢过!

回复内容:

php fsockopen 可以 post json数据吗? 知道的请留下代码,在此谢过!

因为不清楚你所说的 json 数据具体是想要怎么提交, 故分以下两种情况做为展示.

第一种情况: 提交的整个数据就是JSON格式的内容.

1.php

<code class="php"><?php //要提交的数据
$post_fields = array('a'=>'hello', 'b'=>'world', 'c'=>'汉字');

$data = json_encode($post_fields);//转换为JSON格式的字符串

$data = array(
    'POST /123.php HTTP/1.0',//请求的地址
    'Host: localhost',
    'Content-type: application/x-www-form-urlencoded',
    'Content-length: '. strlen($data),//填充数据长度
    '',//请求头与数据的分隔符
    $data//填充数据体
);

//注意修改 域名和端口号
$sock = fsockopen("localhost", 800, $errno, $errstr, 30);

if (!$sock) die("$errstr ($errno) ");

fwrite($sock, implode("\r\n", $data));

$data = '';

while(!feof($sock)){//测试文件指针是否到了文件结束的位置
    $data .= fgets($sock,1024);
}

fclose($sock);

echo $data;</code>
Copy after login

与之对应的123.php文件的代码如下:

<code class="php"><?php $data = file_get_contents('php://input');

var_dump(json_decode($data));</code></code>
Copy after login

代码执行后的结果如下:

<code>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) "汉字"
}
</code>
Copy after login

第二种情况: JSON 格式的数据做为 数据 进行提交.

在上面代码的基础上做如下改动:
1.php

<code>$data = 'xyz=' . json_encode($post_fields);//转换为JSON格式的字符串</code>
Copy after login

php fsockopen post json数据

123.php

<code class="php"><?php var_dump(json_decode($_POST['xyz']));</code></code>
Copy after login

执行结果与之前的一样.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template