【PHP】使用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);

 

posted @ 2019-09-27 15:19  bug毁灭者  阅读(6197)  评论(0编辑  收藏  举报