如何使用file_get_contents在PHP中发布数据?

我使用PHP的函数file_get_contents()来获取URL的内容,然后通过variables$http_response_header处理头文件。

现在的问题是,一些URL需要一些数据发布到URL(例如,login页面)。

我怎么做?

我意识到使用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); 

基本上,你必须创build一个stream,使用正确的选项(该页面上有一个完整的列表) ,并将其用作file_get_contents的第三个参数 – 仅此而已;-)

作为一个旁注:一般来说,要发送HTTP POST请求,我们倾向于使用curl,它提供了很多选项 – 但stream是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"); }