有时候我们需要通过服务端发送请求如常见的api调用,发送请求的方式有几种下面总结一下常用的几种方式
1.通过file_get_contents,使用这种方式要通过stream_context_create模拟post请求
file_get_contents发送post
代码语言:javascript复制//1.php
<?php
$data = array(
'name'=>'alice',
'order'=>45765873422,
'pay'=>76
);
$data = http_build_query($data);
$options = array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-type:application/x-www-form-urlencoded',
'content'=>$data
)
);
$context = stream_context_create($options);//创建资源流
$url = 'http://localhost/OOP/2.php';
$content = file_get_contents($url,false,$context);
echo $content;
//2.php
<?php
if(!empty($_POST)){
var_dump($_POST);
}
//结果
array (size=3)
'name' => string 'alice' (length=5)
'order' => string '45765873422' (length=11)
'pay' => string '76' (length=2)
file_get_contents发送get请求
代码语言:javascript复制<?php
$data = array(
'name'=>'alice',
'order'=>45765873422,
'pay'=>76
);
$data = http_build_query($data);
$url = 'http://localhost/OOP/2.php';
$content = file_get_contents($url.'?'.$data);
echo $content;
curl库发送get
代码语言:javascript复制$url = 'http://www.baidu.com';
$ch = curl_init();//初始化
//设置相应选项
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//将curl_exec()获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($ch,CURLOPT_HEADER,0);//不输出header头
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$output = curl_exec($ch);
curl_close($ch);
// file_put_contents('./1.txt',$output);
return $output;
curl库发送post请求
代码语言:javascript复制<?php
$data = array(
'name'=>'alice',
'order'=>45765873422,
'pay'=>76
);
$data = http_build_query($data);
$url = 'http://localhost/OOP/2.php';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);//POST提交
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST数据
$output = curl_exec($ch);
return $output;