Codeigniter 4 Send Push Notification to Android and IOS Example

In this tutorial, we will show you how to send push notifications to Android and iOS devices using Codeigniter 4.

We will use the Firebase Cloud Messaging (FCM) service to send push notifications to Android and iOS devices.

Prerequisites

Before you start, make sure you have the following:

• Codeigniter 4 installed

• Firebase Cloud Messaging (FCM) account

• Android and iOS devices

Step 1 – Create Firebase Cloud Messaging (FCM) Account

First, you need to create a Firebase Cloud Messaging (FCM) account.

Go to the Firebase Console and create a new project.

Once the project is created, click on the “Add Firebase to your Android app” button.

Enter your Android package name and click on the “Register App” button.

Download the google-services.json file and save it in your project folder.

Now, click on the “Add Firebase to your iOS app” button.

Enter your iOS bundle ID and click on the “Register App” button.

Download the GoogleService-Info.plist file and save it in your project folder.

Step 2 – Create Codeigniter 4 Project

Now, let’s create a Codeigniter 4 project.

Open the terminal and run the following command to create a new Codeigniter 4 project:

composer create-project codeigniter4/appstarter codeigniter-4

Step 3 – Setup Database

Now, let’s setup the database.

Open the .env file and update the database credentials.

database.default.hostname = localhost
database.default.database = ci4
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi

Step 4 – Install FCM Library

Now, let’s install the FCM library.

Run the following command to install the FCM library:

composer require “kreait/firebase-php:^5.0”

Step 5 – Create Controller

Now, let’s create a controller to send push notifications.

Create a file named PushNotification.php in the app/Controllers folder and add the following code:

withServiceAccount($serviceAccount)->create(); $messaging = $firebase->getMessaging(); // Notification data $notificationData = [ ‘title’ => ‘Test Notification’, ‘body’ => ‘This is a test notification from Codeigniter 4.’ ]; // Notification target $target = [ ‘token’ => ‘YOUR_DEVICE_TOKEN’ ]; // Send notification $response = $messaging->send($target, $notificationData); echo ‘

'; print_r($response); echo '

‘; } }

Step 6 – Run Codeigniter 4 Project

Now, let’s run the Codeigniter 4 project.

Open the terminal and run the following command to start the development server:

php spark serve

Now, open your browser and access the following URL:

http://localhost:8080/push-notification/send

You should see the response from the Firebase server.

To send push notifications to Android and IOS mobile using Firebase fcm in ci 4. In this tutorial, you will learn how to send push notifications to Android and IOS mobile using Firebase fcm in CodeIgniter 4 app.

As well as This tutorial will guide the PHP and CodeIgniter developers who want to send FCM(Firebase Cloud Messaging) notifications by using PHP Codeigniter.

Send Push Notification to Android and IOS In Codeigniter 4 App Using Google Firebase

Let’s use the following steps to send push notification to android and IOS using google firebase fcm in codeigniter 4 apps:

  • Step 1 – Setup Codeigniter Project
  • Step 2 – Basic Configurations
  • Step 3 – Create a Controller
  • Step 4 – Create Views
  • Step 5 – Start Development server

Step 1 – Setup Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2 – Basic Configurations

In this step, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create a Controller

In this step, visit to app/Controllers and create a controller name Notification.php. Then add the following code into it:

<?php namespace App\Controllers;

use CodeIgniter\Controller;


class Notification extends Controller
{
    public function index()
    {    
         return view('index');
    }

    public function sendPushNotification()
    {  
        
        $val = $this->validate([
	        'nId' => 'required',
	    ]);

	    $notification_id = $this->request->getVar('nId');
	    $title = 'Demo Notification'; 
	    $message = 'First codeigniter notification for mobile';
	    $d_type    = $this->request->getVar('device_type');  // for android or IOS

	    $accesstoken = 'YOUR FCM KEY';

	    $URL = 'https://fcm.googleapis.com/fcm/send';


	        $post_data = '{
	            "to" : "' . $notification_id . '",
	            "data" : {
	              "body" : "",
	              "title" : "' . $title . '",
	              "type" : "' . $d_type . '",
	              "id" : "' . $id . '",
	              "message" : "' . $message . '",
	            },
	            "notification" : {
	                 "body" : "' . $message . '",
	                 "title" : "' . $title . '",
	                  "type" : "' . $d_type . '",
	                 "id" : "' . $id . '",
	                 "message" : "' . $message . '",
	                "icon" : "new",
	                "sound" : "default"
	                },

	          }';
	        // print_r($post_data);die;

	    $crl = curl_init();

	    $headr = array();
	    $headr[] = 'Content-type: application/json';
	    $headr[] = 'Authorization: ' . $accesstoken;
	    curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

	    curl_setopt($crl, CURLOPT_URL, $URL);
	    curl_setopt($crl, CURLOPT_HTTPHEADER, $headr);

	    curl_setopt($crl, CURLOPT_POST, true);
	    curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
	    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);

	    $rest = curl_exec($crl);

	    if ($rest === false) {
	        // throw new Exception('Curl error: ' . curl_error($crl));
	        //print_r('Curl error: ' . curl_error($crl));
	        $result_noti = 0;
	    } else {

	        $result_noti = 1;
	    }

	    echo view('success');
	}
}


Step 4 – Create Views

In this step, you need to create an index.php file. So visit application/views/ folder and create index.php file. and add the following HTML into your files:.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Send Push Notification using Google FCM Example</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
 <div class="container">
    <br>
    <?= \Config\Services::validation()->listErrors(); ?>

    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('public/index.php/notification/sendPushNotification') ?>" method="post" accept-charset="utf-8">

          <div class="form-group">
            <label for="formGroupExampleInput">Device Type</label>
              <select class="form-control" id="device_type" name="device_type" required="">
              <option value="">Select Device type</option>
               
                    <option value="android">Android</option>
                    <option value="iphone">IOS</option>
  
              </select>
          </div>           

          <div class="form-group">
            <label for="formGroupExampleInput">Notification Id</label>
            <input type="text" name="nId" class="form-control" id="formGroupExampleInput" placeholder="Please enter notification id" required="">
            
          </div> 

          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
        </form>
      </div>

    </div>
 
</div>
</body>
</html>

This below line display error messages on your web page:

<?= \Config\Services::validation()->listErrors(); ?>

Now you need to create success.php file, so go to application/views/ and create success.php file. And put the below code into it:

<!DOCTYPE html>
<html>
<head>
  <title> send push notification to android using codeigniter </title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
	<div class="container mt-5">
	 <h1 class="text-center"> Please check your device ! Thanks</h1>
	</div>
</body>
</html>

Step 5 – Start Development Server

In this step, open your terminal and execute the following command to start development sever:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080/notification

Conclusion

Send push notification to android using PHP CodeIgniter fcm, you have learned how to send push notifications to android and iPhone mobile using firebase fcm in CodeIgniter 4 app.

Recommended CodeIgniter Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?