php curl:我需要一个简单的帖子请求和页面示例的回溯
我想知道如何在curl中发送帖子请求并获取响应页面。
像这样的东西呢:
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://www.example.com/yourscript.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'field1' => 'some date',
'field2' => 'some other data',
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
// result sent by the remote server is in $result
有关可与 curl 一起使用的选项列表,您可以查看curl_setopt
页面。
在这里,您至少必须使用:
CURLOPT_POST
:因为您要发送 POST 请求,而不是 GETCURLOPT_RETURNTRANSFER
:取决于您是要返回请求的结果,还是仅输出它。curl_exec
CURLOPT_POSTFIELDS
:将要发布的数据 - 可以直接编写为字符串,如查询字符串,或使用数组
不要犹豫,阅读PHP手册的卷曲部分;-)
$url = "http://www.example.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$contents = curl_exec($ch);
curl_close($ch);