Send FCM data message & notification to Android, iOS & Web in PHP

In our previous article we learnt how to send FCM data message notification from your server to FCM server using C#. Now for those you want to use PHP instead of C# to send FCM notification we have prepared a fairly simple class.

You just need to follow below four steps and you are done.

  1. Create an object of fcm class
  2. Call setIds method (passing array of registration ids) to set registration ids of your devices
  3. Call setData method to set your notification title, message and id.
  4. Call send method
class fcm
{
	private $url = "https://fcm.googleapis.com/fcm/send";
	private $ids = array();
	private $data = array();
	
	public function setIds($ids)
	{
		$this->ids = $ids;
	}

	public function send()
	{
		if (empty($this->ids))
		{
			return "no id";
		}

		$post = array(
			'registration_ids'  => $this->ids,
			'data'              => $this->data,
		);

		$headers = array(
			'Authorization: key=' . GOOGLE_API_KEY,
			'Content-Type: application/json'
		);
      
		$ch = curl_init();

		curl_setopt( $ch, CURLOPT_URL, $this->url);
		curl_setopt( $ch, CURLOPT_POST, true);
		curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($post));

		// Disabling SSL Certificate support temporarly
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		$result = curl_exec($ch);
		
		if (curl_errno($ch)) 
		{
			$error = curl_error($ch);
			return $error;
		}

		curl_close($ch);

		$obj = json_decode($result, true);

		return "sent on: " . $obj['success'] . " devices";
	}

	public function setData($title, $msg, $id)
	{
		$this->data = array(
			"title" => $$title,
			"msg" => $msg,
			"id" => $id
		);
	}
}

Leave a Reply

Your email address will not be published.