![](/img/trans.png)
[英]get/read raw post data from php://input using CURL and not using file_get_contents
[英]How to post data in PHP using file_get_contents?
我正在使用PHP的函數file_get_contents()
來獲取URL的內容,然后通過變量$http_response_header
處理標頭。
現在的問題是某些URL需要將一些數據發布到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請求,我們傾向於使用curl,它提供了很多選項-但是流是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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.