温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在php中利用curl模拟post请求

发布时间:2021-03-19 16:22:48 来源:亿速云 阅读:196 作者:Leah 栏目:开发技术

如何在php中利用curl模拟post请求?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

具体代码如下:

<?php
$uri = "http://www.cnblogs.com/test.php";//这里换成自己的服务器的地址
// 参数数组
$data = array (
 'name' => 'tanteng'
// 'password' => 'password'
);
$ch = curl_init ();
// print_r($ch);
curl_setopt ( $ch, CURLOPT_URL, $uri );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
print_r($return);

2,远程服务器:

<?php
if(isset($_POST['name'])){
 if(!empty($_POST['name'])){
 echo '您好,',$_POST['name'].'!';
 }
}

下面给大家介绍php中curl模拟post提交多维数组。

今天需要用curl模拟post提交参数,请求同事提供的一个接口;但是传递的参数中,有一个参数的值为数组,用普通的curl post代码提交,会报错误

PHP Notice:  Array to string conversion in /test/functions.php on line 30
Notice: Array to string conversion in /test/functions.php on line 30

代码如下:

<?php
        $param = array(
                'uid' => 123, 
                'uids' => array(12,455), 
                'msgType' => 'WITH',  
                'nick' => 'aaa',   
               );
        $url = "http://cx.com/t.php";
        //通过curl的post方式发送接口请求
        SendDataByCurl($url,$param);
       //通过curl模拟post的请求;
function SendDataByCurl($url,$data=array()){
  //对空格进行转义
  $url = str_replace(' ','+',$url);
  $ch = curl_init();
  //设置选项,包括URL
  curl_setopt($ch, CURLOPT_URL, "$url");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟 
   // POST数据
  curl_setopt($ch, CURLOPT_POST, 1);
  // 把post的变量加上
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  //执行并获取url地址的内容
  $output = curl_exec($ch);
  //释放curl句柄
  curl_close($ch);
  return $output;
}

经过修改上面代码,可以完成提交数组的功能,而不会报php notice,代码如下:

//通过curl模拟post的请求;
function SendDataByCurl($url,$data=array()){
  //对空格进行转义
  $url = str_replace(' ','+',$url);
  $ch = curl_init();
  //设置选项,包括URL
  curl_setopt($ch, CURLOPT_URL, "$url");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟 
   // POST数据
  curl_setopt($ch, CURLOPT_POST, 1);
  // 把post的变量加上
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  //所需传的数组用http_bulid_query()函数处理一下,就ok了
  //执行并获取url地址的内容
  $output = curl_exec($ch);
  $errorCode = curl_errno($ch);
  //释放curl句柄
  curl_close($ch);
  if(0 !== $errorCode) {
    return false;
  }
  return $output;
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI