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

如何使用&传递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条)

相关推荐 更多相似问题