Home >Backend Development >PHP Tutorial >How to send GET and POST requests through file_get_contents()? (Method introduction)

How to send GET and POST requests through file_get_contents()? (Method introduction)

青灯夜游
青灯夜游forward
2020-07-20 16:57:555554browse

How to send GET and POST requests through file_get_contents()? (Method introduction)

The server performs HTTP requests. What everyone often uses is CURL. The curl tool is indeed a good data file transfer tool. In addition, there are other tools that can achieve this. Function?

Now I will introduce you to a very common toolfile_get_content()

Nani, isn’t this a PHP file operation function??? Can GET POST requests also be implemented? ? ?

I can tell you clearly here that it is absolutely possible! ! !

Without further ado, let’s get straight to the code. If you have any questions, please call me. Remember to bring medical expenses

1. [GET request]

$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 request】

$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);

Related tutorial recommendations: "PHP Tutorial"

The above is the detailed content of How to send GET and POST requests through file_get_contents()? (Method introduction). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete