在PHP開發的過程中經常需要發送POST請求,POST相比GET要安全很多,而且傳輸的資料量也較大。下面PHP程式員雷雪松就帶大家一起總結下PHP發送POST請求的幾種常用方式,分別使用curl、file_get_content來實現POST請求和傳遞參數。
1、curl實現PHP POST請求和傳遞參數。
$data=array("username"=>"raykaeso","name"=>"雷雪松");//post參數
$url="http://www.111cn.net";
$ch = curl_init();//建立串連
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//將數群組轉換為URL請求字串,否則有些時候可能服務端接收不到參數
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); //接收服務端範圍的html代碼而不是直接瀏覽器輸出
curl_setopt($ch, CURLOPT_HEADER, false);
$responds = curl_exec($ch);//接受響應
curl_close($ch);//關閉串連
2、file_get_content實現PHP POST請求和傳遞參數
$data=array("username"=>"raykaeso","name"=>"雷雪松");//post參數
$url="http://www.111cn.net";
$content = http_build_query($data);
$length = strlen($content);
$options = array(
'http' => array(
'method' => 'POST',
'header' =>
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-length: $length \r\n",
'content' => $content
)
);
file_get_contents($url, false, stream_context_create($options));