[英]Get POST data from file_get_contents
我關注了這篇文章,以了解如何將數據傳遞到php的file_get_contents函數,但我似乎無法使用以下方法獲取數據:
$data = $_POST['my_param']; // Where my_param is the name of the parameter passed
有人知道如何在我使用file_get_contents調用的腳本中取回發送到file_get_contents的參數的值嗎?
提前致謝
有一個例子@ php.net http://php.net/manual/en/function.file-get-contents.php#102575
碼:
<?php
/**
make an http POST request and return the response content and headers
@param string $url url of the requested script
@param array $data hash array of request variables
@return returns a hash array with response content and headers in the following form:
array ('content'=>'<html></html>'
, 'headers'=>array ('HTTP/1.1 200 OK', 'Connection: close', ...)
)
*/
function http_post ($url, $data)
{
$data_url = http_build_query ($data);
$data_len = strlen ($data_url);
return array ('content'=>file_get_contents ($url, false, stream_context_create (array ('http'=>array ('method'=>'POST'
, 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
, 'content'=>$data_url
))))
, 'headers'=>$http_response_header
);
}
?>
但是在實際應用中,我不會使用該方法。 我建議您改用curl。
curl的簡單示例:
<?php
$ch = curl_init(); // create curl handle
$url = "http://www.google.com";
/**
* For https, there are more options that you must define, these you can get from php.net
*/
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query(['array_of_your_post_data']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3); //timeout in seconds
curl_setopt($ch,CURLOPT_TIMEOUT, 20); // same for here. Timeout in seconds.
$response = curl_exec($ch);
curl_close ($ch); //close curl handle
echo $response;
?>
使用curl,您可以100%地從$ _POST獲得您的post參數。 我在數十個項目中使用過curl,以前從未失敗過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.