1. 程式人生 > >使用file_get_contents() 傳送GET、POST請求

使用file_get_contents() 傳送GET、POST請求

伺服器端執行HTTP請求,大家經常使用的就是CURL,curl工具的確是很好的資料檔案傳輸工具,那麼除此之外還有其他的工具能實現這個功能嗎?

現在為你介紹一個很常見的工具 file_get_content()  

納尼,這不是PHP檔案操作函式嗎??? 竟然還能實現GET POST 請求???

這裡可以很明確的告訴你,完全可以!!!

廢話不多說,直接上程式碼。有問題來打我、記得帶醫藥費

1、【GET請求】

1 $data = array( 'name'=>'zhezhao','age'=>'23');
2 $query = http_build_query($data); 
3 $url = 'http://localhost/get.php';//這裡一定要寫完整的服務頁面地址,否則php程式不會執行 
4 $result = file_get_contents($url.'?'.$query); 

2、【POST請求】

1 $data = array('user'=>'jiaxiaozi','passwd'=>'123456');
2 $requestBody = http_build_query($data);
3 $context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n"."Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]);
4 $response = file_get_contents('http://server.test.net/login', false, $context);

&n