协慌网

登录 贡献 社区

如何使用 PHP 发送 POST 请求?

实际上,我想阅读搜索查询之后的内容,当它完成时。问题在于 URL 仅接受POST方法,并且对GET方法不执行任何操作...

domdocumentfile_get_contents()的帮助下阅读所有内容。有什么方法可以让我使用POST方法发送参数,然后通过PHP读取内容?

答案

PHP5 的无 CURL 方法:

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

有关该方法以及如何添加标头的更多信息,请参见 PHP 手册,例如:

您可以使用cURL

<?php
//The url you wish to send the POST request to
$url = $file_name;

//The data you want to send via POST
$fields = [
    '__VIEWSTATE '      => $state,
    '__EVENTVALIDATION' => $valid,
    'btnSubmit'         => 'Submit'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 

//execute post
$result = curl_exec($ch);
echo $result;
?>

我使用以下函数通过 curl 发布数据。 $ data 是要发布的字段数组(将使用 http_build_query 正确编码)。使用 application / x-www-form-urlencoded 对数据进行编码。

function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

@Edward 提到可以省略 http_build_query,因为 curl 将正确地编码传递给 CURLOPT_POSTFIELDS 参数的数组,但是建议在这种情况下,数据将使用 multipart / form-data 进行编码。

我将此函数与期望使用 application / x-www-form-urlencoded 编码的 API 一起使用。这就是为什么我使用 http_build_query()的原因。