Search code examples
phplaravelflutterlaravel-7php-curl

Curl request not working in laravel 7 but working inside the command line


I making an app in flutter with laravel 7 as the backend everything is cool except when I try to send notification using firebase I can't seem to let curl to work.

I tried this code but curl doesn't seem to work, and if I try the code on php on server directly from the command line the code works.

My php version is 7.4.12 and the system is centos 8

the frontend:

<form method="POST" action="{{route('bulksend')}}">
  {{ csrf_field()}}
  <label>Title</label>
  <input type="text" hint="Title" name="title">
  <br>
  <label>Body</label>
  <input type="text" hint="Body" name="body">
  <br>
  <label>Image URL</label>
  <input type="text" hint="Image URL" name="img">
  <br>
  <label>ID</label>
  <input type="text" hint="Image URL" name="id">
  <br>
  <input type="submit"/>
</form>

The controller method:

public function bulksend(Request $req)
{
    $url = 'https://fcm.googleapis.com/fcm/send';
    $dataArr = array('click_action' => 'FLUTTER_NOTIFICATION_CLICK', 'id' => $req->id, 'status' => "done");
    $notification = array('title' => $req->title, 'text' => $req->body, 'image' => $req->img, 'sound' => 'default', 'badge' => '1',);
    $arrayToSend = array('to' => "my device_token", 'notification' => $notification, 'data' => $dataArr, 'priority' => 'high');
    $fields = json_encode($arrayToSend);
    $headers = array(
        'Authorization: key=' . "my auth",
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    $result = curl_exec($ch);

    curl_close($ch);
    print_r($result);
    return $result;
}

The output is just an empty page. while in the console it prints a success. Thank you for your help.


Solution

  • You need to install php-curl extension.
    The Response of any curl php request will be 0, or false.

    In the server that is not working add extension like this :

    sudo yum install -y  php-curl
    

    and then restart your web server

    sudo systemctl restart httpd.service