PHP发送请求

有时候我们需要通过服务端发送请求如常见的api调用,发送请求的方式有几种下面总结一下常用的几种方式
1.通过file_get_contents,使用这种方式要通过stream_context_create模拟post请求
file_get_contents发送post

//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请求

<?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

$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请求

<?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;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值