首頁  >  文章  >  後端開發  >  如何透過file_get_contents()傳送GET、POST請求? (方法介紹)

如何透過file_get_contents()傳送GET、POST請求? (方法介紹)

青灯夜游
青灯夜游轉載
2020-07-20 16:57:555438瀏覽

如何透過file_get_contents()傳送GET、POST請求? (方法介紹)

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

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

納尼,這不是PHP檔案運算子嗎??? 竟然還能實現GET POST 請求? ? ?

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

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

1、【GET請求】

$data = array( 'name'=>'zhezhao','age'=>'23');
$query = http_build_query($data); 
$url = 'http://localhost/get.php';//这里一定要写完整的服务页面地址,否则php程序不会运行 
$result = file_get_contents($url.'?'.$query);

2、【 POST請求】

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

相關教學推薦:《PHP教程

以上是如何透過file_get_contents()傳送GET、POST請求? (方法介紹)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除