php中模擬post,get請求和接受請求詳細講解
在php中我們經常用到curl拓展來進行模擬post、get請求,下面就來具體說說怎麽模擬:
一、首先模擬post請求:
function http_post_data($url, $query_data,$timeout=30) {
if(is_array($query_data)){
$post_str = http_build_query($query_data); //變成 a=1&b=2形式 會進行urlencode()轉換
} $curl = curl_init(); // 初始化curlcurl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); // 過濾HTTP頭 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 顯示輸出結果 curl_setopt($curl, CURLOPT_POST, true); // post方式 curl_setopt($curl, CURLOPT_POSTFIELDS, $post_str); // post傳輸數據 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); // 設置等待時間 curl_setopt($ch,CURLOPT_TIMEOUT,$timeout); // 設置超時 if(strtolower(substr($this->url,0,5))==‘https‘){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); } //curl_setopt($curl,CURLOPT_CAINFO,dirname(__FILE__).‘/cacert.pem‘) //如果地址是https協議,且CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST打開了,則需要加載證書
//根據http://curl.haxx.se/ca/cacert.pem 下載的證書,添加上面註冊的這個選項就可以運行正常了$header = array( "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" ); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); $content = curl_exec($curl);//返回內容 $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);//返回狀態碼 curl_close($curl); if($status==‘200‘) return $content; else return false; }
模擬get請求就很簡單了,直接將post方式改為false,將post傳輸數據項註釋;然後將請求的參數拼接到路徑後面就可以了。
上面這種方式如果我們傳送數組 或者 a=1&b=2 這樣格式的字符串,接受這樣的傳送,直接用$_POST 或者$_REQUEST就可以獲取對應參數的值,至於其他的怎麽下面再說。
二、不同的請求頭
但有時候我們想要傳送json和文件時上面這種方式可能就有點行不通,需要像下面一樣該改變請求頭
請求json數據:
$header[] = "Content-Type: application/json; charset=utf-8";//聲明請求的內容為json $header[] = "Content-Length:".strlen(json_encode($data));//請求內容的長度
上傳文件:
$header[] = "Content-Type:multipart/form-data";//用$_FILES接受傳送的文件
請求html數據:
$header[] = "Content-Type:text/html;charset=utf-8";
請求xml數據:
$header[] = "Content-Type:text/xml;charset=utf-8";
還有一種:這種方式,如果瀏覽器接受到內容,會直接當做純文本,不會進行html或者xml解析。
$header[] = "Content-Type:text/plain;charset=utf-8";
三、接受請求的幾種方式
1、數組或者a=1&b=2類的字符串
這個不用多說直接用我們常用的$_GET、$_POST、$_REQUEST就可以接受
2、json、xml、html或者其他字符串
PHP默認只識別application/x-www.form-urlencoded標準的數據類型,對xml內容、json內容、html內容的內容無法解析為$_POST數組,因此會保留原型,可以交給file_get_contents(‘php://input’)接收,也可以用$GLOBALS[‘HTTP_RAW_POST_DATA‘]。
$xml = file_get_contents("php://input"); //或者 $xml = $GLOBALS[‘HTTP_RAW_POST_DATA‘];
php://input 允許讀取 POST 的原始數據。和$GLOBALS[‘HTTP_RAW_POST_DATA‘] 比起來,它給內存帶來的壓力較小,並且不需要任何特殊的 php.ini 設置。同時兩者皆不能用於接收enctype="multipart/form-data"形式的數據。
四、file_get_contents()模擬請求
function post($url, $content){ $ctx = array( ‘http‘ => array( ‘method‘ => ‘POST‘,//或者GET ‘header‘ => "Content-Type: application/x-www-form-urlencoded", ‘content‘ => $content ) ); return file_get_contents($url, false, stream_context_create($ctx)); }
這種方式也可以快速模擬post、get請求,不過這種方式在訪問量不大的情況下還沒什麽問題,如果訪問量大可能就會出問題;所以一般在項目中不太推薦這種請求方式。
php中模擬post,get請求和接受請求詳細講解