如何使用的file_get_contents在PHP发布数据?
-
20-09-2019 - |
题
我使用PHP的功能file_get_contents()
抓取的URL的内容,然后我处理通过可变$http_response_header
头。
现在的问题是,一些网址需要一些数据要被发布到的URL(例如,登录页)。
我该怎么做呢?
我体会到使用stream_context我可能能够做到这一点,但我不完全清楚。
感谢。
解决方案
使用 file_get_contents
发送的HTTP POST请求并不难,实际上是:你猜到,你必须使用$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);
基本上,你必须创建一个流,它具有正确的选项的(有该网页上的完整列表)的,并把它作为第三个参数来file_get_contents
- 仅此而已;-)
,点击 作为一个旁注:一般来说,发送HTTP POST请求,我们倾向于使用卷曲,它提供了很多选择的所有 - 但流的PHP的好东西,没有人知道......太糟糕了一个..
其他提示
的替代,也可以使用的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");
}
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$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");
}
不隶属于 StackOverflow