好长时间没自己写fsockopen远程访问了,习惯了curl的强大,查了下资料写了段post方式代码:
<?php
$url = 'test.fsk.com';
$fp = @fsockopen($url, 80, $errno, $errstr, 3);//远程打开url
$str = "key1=val1&key2=val2"; //post数据
$flag = 0; //区分header和返回数据
$msg = '';//获取返回的json数据
if (!$fp) { //失败
echo "$errstr ($errno)<br />\n";
} else {
////根据实际调用填写url路径和get方式参数
$out = "POST /controller/action?query_string HTTP/1.1\r\n";
$out .= "Host: " . $url . "\r\n";
//post方式必须设置该type
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
//post方式必须设置该length
$out .= "Content-Length: " . strlen($str) . "\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= $str . "\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
$s = fgets($fp, 1024);
$s = trim($s);
//echo $s."<br />";
if(empty($s)){
$flag = 1;
}elseif($flag == 1){//读取返回的内容
$msg .= $s;
}
}
fclose($fp);
//打印数据
var_dump(json_decode($msg));
}