Skip to content

How to use Twilio to send SMS with CodeIgniter

Last updated on November 18, 2022

In this CodeIgniter Twilio tutorial, I would like to show sending SMS from the CodeIgniter app using the Twilio library. Twilio is a cloud communications platform for building SMS, Voice & Messaging applications.

Here are the steps to send SMS messages using Twilio APIs in the CodeIgniter 3 application:

Step 1: Download and install CodeIgniter.

Step 2: Run the below composer command to download twilio/sdk library from your project folder. It will create a new folder called “vendor” and it will download the Twilio library into it.

$ composer require twilio/sdk
codeigniter twilio

Here is my directory structure after installing Twillo SDK.

Step 3: Open application/config/config.php file and set your vendor directory path

$config['composer_autoload'] = 'vendor/autoload.php';

Step 4: Use twilio/sdk library inside your controller, here is the sample:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Twilio\Rest\Client;

class Welcome extends CI_Controller {

	public function index()
	{
		$data = ['phone' => '+919703132428', 'text' => 'Hello, CI'];
		print_r($this->sendSMS($data));
	}

	protected function sendSMS($data) {
          // Your Account SID and Auth Token from twilio.com/console
            $sid = 'your_sid';
            $token = 'your_token';
	    $client = new Client($sid, $token);
			
            // Use the client to do fun stuff like send text messages!
             return $client->messages->create(
                // the number you'd like to send the message to
                $data['phone'],
                array(
                    // A Twilio phone number you purchased at twilio.com/console
                    "from" => "+your Twilio number",
                    // the body of the text message you'd like to send
                    'body' => $data['text']
                )
            );
    }
}

Step 5: Let’s run the application with a PHP Built-in web server for testing, and issue the following command from the root of the project.

PS C:\Users\arjun\Desktop\ci-Twilio> php -S localhost:3030
PHP 7.1.6 Development Server started at Tue May 15 23:55:33 2018
Listening on http://localhost:3030

Step 6: Now if you access the http://localhost:3030 the given number will receive the message/SMS.

4 1 vote
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments