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)

青灯夜游
Release: 2023-04-09 10:00:01
forward
5575 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template