PHP复用curl请求遇到的请求参数混乱的问题

    xiaoxiao2025-04-14  12

    PHP复用curl请求遇到的请求参数混乱的问题

    在调开放平台的一个查询接口的时候,开始一直是好好的,某种特定的情况下会报签名失败!不能理解,接口一直运行的好好的,没有改动,一定是哪里出现了问题!

    经过若干次尝试,终于复现问题。找到了这个“特定情况”。如果我在请求这个查询接口,称之为A接口吧,请求A接口之前,请求了同一域名下的另外一个接口B,这时候就会出现“签名失败”的问题。百分百复现。

    进一步分析框架发现,在进行接口请求时,采用的httprequest 根据域名 复用了curl请求以达到节省每次curl_init的资源开销的目的:

    [php]  view plain  copy     public static function get_curl($host_id) {           // TODO max 20 curl           if (isset(self::$curl_state[$host_id])) {               $ch = self::get_curl_from_pool($host_id);               if ($ch === false) {                   $ch = self::get_curl_create($host_id);               }           } else {               $ch = self::get_curl_create($host_id);           }                      return $ch;       }   经过尝试发现,如果不适用curl连接池,上述问题是不会出现的。那么问题就出在使用了curl连接池造成了某种影响。

    既然接口方返回签名失败,那就要先看看请求到接口方的参数到底是什么样子的。接下来就是把接口方的接口地址换成本地的测试接口地址,经过上述请求过程,赫然发现,请求接口B的参数在请求接口A的时候,一并传过去了!就是在复用curl请求的时候,连请求参数也一并复用了?!

    进一步发现,A接口的请求方式是GET,B接口的请求方式是POST!如果保持两个接口的请求方式一致,则不会出现上述问题!

    到此为止,事情的脉络已经基本清晰了。到底什么原因导致请求参数被复用了呢?还是要从框架找原因。

    [php]  view plain  copy     private function curl_setopt() {           ...           $this->load_query_fields();           $this->load_post_fields();                      if ($this->method) {               curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method));               $this->curl_cli .= " -X \"{$this->method}\"";           }           ...   }   [php]  view plain  copy     private function load_query_fields() {           $this->query_string = '';           if (empty($this->query_fields)) {               return;           }                      foreach ($this->query_fields as $name => $value) {               $pairs[] = $name . '=' . $value;           }                      if($pairs){               $this->query_string = implode('&'$pairs);           }           curl_setopt($this->ch, CURLOPT_URL, $this->url . '?' . $this->query_string);       }              private function load_post_fields() {           if (empty($this->post_fields)) {               return;           }           if(true == $this->has_upload){               curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->post_fields);           }           else{               curl_setopt($this->ch, CURLOPT_POSTFIELDS, self::http_build_query($this->post_fields));           }           foreach ($this->post_fields as $name => $value) {               if ($this->has_upload) {                   $this->curl_cli .= " --form \"" . $name . '=' . $value . "\"";               } else {                   $pairs[] = $name . '=' . $value;               }           }                      if (!empty($pairs)) {               $this->curl_cli .= " -d \"" . implode('&'$pairs) . "\"";           }       }  

    并没有使用curl_setopt($ch,CURLOPT_POST)来限定此次请求是POST还是GET,因此,第二次请求时用的GET方式,但是由于没有post参数,上一次请求的 post field不会被覆盖掉。导致参数被复用的问题。

    转载请注明原文地址: https://ju.6miu.com/read-1298046.html
    最新回复(0)