18910140161

php使用 file_get_contents 函数发送post与get请求的方法

顺晟科技

2021-06-28 17:25:34

104

在php脚本中请求远程资源链接一般都是使用curl工具,curl即可以发送GET请求也可以发送POST请求,除了curl工具之外php也提示一个 file_get_content() 工具,他的作用可curl差不多,即可以发送GET请求也可以发送POST请求,具体的使用方法,可以参考下面的内容。

php file_get_contents() 请求一个网址的方法

示例

//这里的网址请求没有任何的参数
$response = file_get_contents('http://localhost/get.php');
php file_get_contents() 发送GET请求的方法

示例:

$data = array( 'username'=>'zhezhao','userpass'=>'123');
$query = http_build_query($data);
//请求的地址
$url = 'http://localhost/get.php';
$result = file_get_contents($url.'?'.$query);
php file_get_contents() 发送POST请求的方法

示例:

$data = array( 'username'=>'zhezhao','userpass'=>'123');
$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://localhost/get.php', false, $context);
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航