drqn5418 2017-11-30 14:47
浏览 75
已采纳

为什么curl_exec()在我的Web服务中返回响应?

Why curl_exec() is returning an array in my web service?

I created a web service to send push notifications with Firebase. Everthing works perfectly well except that the result of notification is coming with the server response, even if I didn't ask it.

public function send_notification($recipient_id,$recipient_type,$request_status)
{
    $url = "https://fcm.googleapis.com/fcm/send";
    $token = $user_device_token;
    $notification = array(
        'title' => $title,
        'text' => $body,
        'sound' => 'default',
        'badge' => '1'
    );
    $arrayToSend = array(
        'to' => $token,
        'notification' => $notification,
        'priority' => 'high'
    );

    $json = json_encode($arrayToSend);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key=' . $server_key;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    //Send the request
    error_reporting(E_ERROR);
    $response_notification = curl_exec($ch);
    if ($response_notification === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

    return $response_notification;

}

Here is how I call the send_notification() function:

$this->send_notification($request->provider_id,'provider',0);

Then I print a success message for the client side part of the webapp:

$response_array = array(
    'success' => true,
    'request_id' => $requests->id,
    'current_provider' => $request->provider_id,
    'address' => $requests->s_address,
    'latitude' => $requests->s_latitude,
    'longitude' => $requests->s_longitude,
);
$response = response()->json($response_array, 200);
return $response; 

Even if I didn't ask, there is the notification response generated when calling curl_exec($ch), attached to the response.

enter image description here

The first line is the one I don't want and I am not expecting.

  • 写回答

1条回答 默认 最新

  • doupu5941 2017-11-30 14:49
    关注

    The default behaviour of curl_exec is to print the response directly to stdout. If you want to just access the response as a variable instead, you need to set an additional option:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密