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 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值