Par*_*pra 287 php http http-post file-get-contents
我正在使用PHP的函数file_get_contents()来获取URL的内容,然后我通过变量处理标头$http_response_header.
现在问题是某些URL需要将一些数据发布到URL(例如,登录页面).
我怎么做?
我意识到使用stream_context我可以做到这一点,但我并不完全清楚.
谢谢.
Pas*_*TIN 574
使用发送HTTP POST请求file_get_contents并不难,实际上:正如您猜测的那样,您必须使用该$context参数.
PHP手册中给出了一个示例,在此页面:HTTP上下文选项 (引用):
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Run Code Online (Sandbox Code Playgroud)
基本上,你必须使用正确的选项创建一个流(该页面上有一个完整的列表),并将其用作第三个参数file_get_contents- 仅此而已;-)
作为旁注:一般来说,为了发送HTTP POST请求,我们倾向于使用curl,它提供了很多选项 - 但是流是PHP的好东西之一,没有人知道......太糟糕了.. .
Mac*_*ric 20
另一种方法,你也可以使用fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
316002 次 |
| 最近记录: |