为什么在服务器端PHP用curl发起的get请求,获取不到返回值呢?
发布于 5 年前 作者 huxiuying 8781 次浏览 来自 问答

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

在服务器端PHP用curl发起的get请求,获取不到返回结果呢?打印$content为空值

直接在浏览器里加参数访问是可以获取到返回结果的,

public function get($url, $params = array(), $headers = array()) {
    $url = $this -> buildUrl($url, $params);
    $headers = array_merge($this -> headers, $this -> buildHeaders($headers));

    $ch = curl_init();
    $this -> prepare($ch);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this -> socketTimeout);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this -> connectTimeout);
    $content = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code === 0) {
      //原生抛出异常会报错 //throw new Exception(curl_error($ch));
      $content = curl_error($ch);
    }

    curl_close($ch);
    return array('code' => $code, 'content' => $content, );
  }

回到顶部