duancan1732 2019-03-28 07:31
浏览 277
已采纳

如何使用&传递curl中的数组?

I made one curl call function it's like below:

public function curl($url, $post = array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.12) Gecko/20070508 Firefox/1.5.0.12");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $this->ckfile);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $this->ckfile);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_URL, $url);
    if(!empty($post)){
        $post_string = "";
        foreach($post as $key=>$value) { $post_string .= $key.'='.urlencode($value).'&'; }
        rtrim($post_string, '&');
        curl_setopt($ch,CURLOPT_POST, count($post));
        curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
    }
    $res = curl_exec($ch);
    if (curl_errno($ch)) {
        $this->deliver_responce('201','Couldn\'t send request: ' . curl_error($ch));exit();
    }
    else {
        $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($resultStatus == 200) {
            //echo "Post Successfully!";
            return true;
        }
        else{
            $this->deliver_responce('200','Request failed: HTTP status code: ' . $resultStatus);exit();
        }
    }
}

I have to call it with URL and array that I want to post. It's working when the array has key and value but not working when I have nested array. It’s working for:

array(
    'id'=>1,
    'name'=>'apple'
)

but not working for

array(
    'id'=>5,
    'cmd'=>array('password','encrypt','decrypt')
)

I think problem is at:

foreach($post as $key=>$value) { $post_string .= $key.'='.urlencode($value).'&'; }

In my function but I don't know how to do it.

  • 写回答

3条回答 默认 最新

  • douci1196 2019-03-29 10:49
    关注

    it's solved changing foreach loop like

    foreach($post as $key=>$value) { 
        if (is_array($value)) {
            foreach ($value as $val) {
                $post_string .= $key.'[]='.urlencode($val).'&';
            }
        } 
        else{ 
            $post_string .= $key.'='.urlencode($value).'&'; 
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?