那么如果使用更复杂的请求呢?如调用res api。使用post提交参数,参数格式为json的。
如果访问自签名的https网站(或者ssl证书失效的https网站),需要禁用ssl证书效验呢?
如果获取数据后需要查看响应头(Response headers)的值呢?
1. Post提交请求,并自定义请求头(Request Header)
$json = "{\"session\": \"". $token . "\",\"ids\": [\"". $fid . "\"]}";
$length = strlen($json);
$http = array('method' => 'POST','header' => "Content-Type: application/json\r\n" . "Content-Length: $length \r\n", 'content' => $json);
$options = array('http' => $http);
$json = file_get_contents($url, false, stream_context_create($options));
$data = json_decode($json, true);
$length = strlen($json);
$http = array('method' => 'POST','header' => "Content-Type: application/json\r\n" . "Content-Length: $length \r\n", 'content' => $json);
$options = array('http' => $http);
$json = file_get_contents($url, false, stream_context_create($options));
$data = json_decode($json, true);
2. Post表单数据
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(array('foo'=>'bar'))
));
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(array('foo'=>'bar'))
));
3. 访问https网站时禁用ssl证书效验
$options = array(
'ssl' => array( 'verify_peer' => false)
);
'ssl' => array( 'verify_peer' => false)
);
4. 获取响应头信息
使用php的预定义变量:$http_response_header。
注意:这个变量的作用域是在调用 file_get_contents的域内。
file_get_contents("http://example.com");
var_dump($http_response_header); // 变量在本地作用域中填充
var_dump($http_response_header); // 变量在本地作用域中填充
头信息类似如下:
array(6) {
[0]=> string(15) "HTTP/1.1 200 OK"
[1]=> string(35) "Date: Thu, 26 Dec 2024 01:55:09 GMT"
[2]=> string(14) "Server: Apache"
[3]=> string(32) "Vary: User-Agent,Accept-Encoding"
[4]=> string(17) "Connection: close"
[5]=> string(23) "Content-Type: text/html"
}
[0]=> string(15) "HTTP/1.1 200 OK"
[1]=> string(35) "Date: Thu, 26 Dec 2024 01:55:09 GMT"
[2]=> string(14) "Server: Apache"
[3]=> string(32) "Vary: User-Agent,Accept-Encoding"
[4]=> string(17) "Connection: close"
[5]=> string(23) "Content-Type: text/html"
}
补充说明
如果php编译时使用了参数 --with-curlwrappers, 那么在自定义头信息时可以使用数组,而不用拼接字符串。
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" . "Cookie: foo=bar\r\n"
)
);
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>array("Accept-language: en","Cookie: foo=bar")
)
);
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" . "Cookie: foo=bar\r\n"
)
);
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>array("Accept-language: en","Cookie: foo=bar")
)
);