首页 > 解决方案 > PHP:在 cURL GET 请求之后立即发出 cURL POST 请求

问题描述

我正在尝试在我的第一个 cURL 请求之后立即执行 cURL POST 请求。我是 PHP 和服务器端的新手。

我的第一个请求是 GET。通过 API 响应,我正在执行if error -> curl_close else -> new cURL POST request。但是第二个请求什么也没返回。我已经尝试过使用“传统邮递员 JSON 请求”并且请求有效,所以问题出在我的 PHP 代码中。

/* First we try to have id user from his mail*/

$curl = curl_init();   
$usermail = "user@mail.com";

//url = url + email
$gen_url = "https://myendpoint.com/manage/v1/user?search_text=";
$url = $gen_url.$usermail;

//GET request return all info about user, we do this to have his userid 
curl_setopt_array($curl, array(
  CURLOPT_URL => $url, 
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer $tokenDecode",
    "Content-Type: application/x-www-form-urlencoded",
  ),
));

$response2 = curl_exec($curl);
$err = curl_error($curl);

if ($err) {
  echo "cURL Error #:" . $err;
  curl_close($curl);
} else {
  $userInfo = json_decode($response2, true);
  $userId = $userInfo["data"]["items"][0]["user_id"] . "<br>"; 

  /* We have the user_id, we can POST on user's additionnal fields */

  $gen_url2="https://myendpoint.com/manage/v1/user/";   
  $url2= $gen_url2.$userId;

  curl_setopt_array($curl, array(
    CURLOPT_URL => $url2,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "PUT",
    CURLOPT_POSTFIELDS => "{'additional_fields':[{'id':98,'value':2}]",
    CURLOPT_HTTPHEADER => array(
      "Authorization: Bearer $tokenDecode",
      "Content-Type: application/json",
    ),
  ));

  $response3 = curl_exec($curl);
  $err2 = curl_error($curl);

  curl_close($curl);

  if ($err2) {
    echo "cURL Error #:" . $err2;
  } else {
    echo $response3; //Show nothing
  }
  }   

我的 GET 请求工作,我能够返回我想要的。但似乎我的第二个 cURL 请求没有发送,它没有返回任何响应。我正在做或认为的方式是错误的吗?还是我错过了什么?

谢谢

标签: phpcurl

解决方案


如果 GET 请求正常,您可以在为 POST 请求设置数据之前通过curl_resethttps://www.php.net/manual/en/function.curl-reset.php )重置 curl 数据。


推荐阅读