Learn PHP Programming with Ahex | Ahex Technologies https://ahex.co/category/php/ Ahex Technologies focuses on offshore outsourcing, by providing innovative and quality services and value creation for our clients. Wed, 18 Oct 2023 08:14:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 202019870 Object Oriented Programming https://ahex.co/object-oriented-programming/?utm_source=rss&utm_medium=rss&utm_campaign=object-oriented-programming Thu, 12 Mar 2020 11:40:56 +0000 https://www.ahex.co/?p=6461 Object-Oriented Programming Context:-    The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function of the class. So, we can build the real-time big applications by using the classes, methods, access specifiers, access...

The post Object Oriented Programming appeared first on Welcome to Ahex Technologies.

]]>
Object-Oriented Programming

Context:-   

The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function of the class.

So, we can build the real-time big applications by using the classes, methods, access specifiers, access modifiers, hiding data, showing data, extend the additional code with another class

OOP is a type of software design this design will useful for programming approach

And it is well suited for programs that are large, complex, actively updated and well-maintained projects.

How it works:-

A class that contains planning to to-do the work. And it doesn’t consume any space in memory of the machine

After you execute a class it will convert into the object and takes space in memory of the machine

The class structure is for code re-usability means the superclass is allowed to inherit the features of methods and variables of the superclass (parent class).

A feature of objects is an object’s procedures that can access and often modify the data fields of the object with which they are associated

Examples:-

A civil engineer gives a plan of design for building a house on a chart (CLASS). Then the workers will build the real house according to design (OBJECT).

Similarly, a programmer can give the class a logical structure text in a file (CLASS). Then after the system will run on execution and create data in memory according to login given (OBJECT).

Class:-

Class is a text which consists of the logical operations of the object.

And class can be extended with other classes using specific keywords

That class extension is useful for the project without affecting the entire core project.

And it also useful to debug the newly updated classes

The class consists mainly

  1. Variables
  2. Methods

The class architecture will like the variables can handle the data

Syntax:

  1. class<class_name>{
  2. variable;
  3. method;
  4. }

In all object-oriented programming languages fallowing the same structure of the class

  1. Classes
  2. Interfaces

Access Specifiers in class:-

Inside of the class, all are class variables

Inside of the method all are method variables

In programming, we can divide the variables and methods with access specifiers

  1. public
  2. private
  3. protected
  1. Public 
  2. Can access to other classes
  1. Private 
  2. Will hide the data in the current class itself.
  1. Protected 
  2. Will show data to the base class and derived-class only except all other classes it will hide

 

Method:

The main aim of the method is for writing a specific piece of code and returning its output

It’s always possible to build great things with certain blocks with a clear blueprint

Making everything is possible with clear objects

  1. The method is a part of the class. A class can be full filled with n number of methods
  2. A method can get the inputs through the parentheses and produces output when it gets called.
  3. A method is a set of code wizard

Example:-

In mathematics, we have the functions like f(x) = x*x same concept in programming implemented

Simpler a function in the program is a block of code performs a specific task and returns task output

Syntax:

  1. class<class_name>{
  2. function <method_name>(inputs){
  3. //task logic
  4. //return logic output
  5. }
  6. }

Object:

We use a specific keyword for converting class into the object.

After converting into the object all methods and variables will become the properties of the object

So, we could create the unique name of n number of objects with a different name

And also could interact with other objects with unique names

Conclusion:-

  1. This is about the main theme of object-oriented programming.
  2. For security purpose, access specifiers and access modifiers are implemented in object-oriented programming

And the architecture of object-oriented programming like the following.

  1. A class build with piece of code with certain methods, and variables
  2. All of those pieces of classes will build packages or modules.
  3. All of these modules or packages will build the entire project.

The post Object Oriented Programming appeared first on Welcome to Ahex Technologies.

]]>
6461
Test Driven Development Using Laravel https://ahex.co/test-driven-development-using-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=test-driven-development-using-laravel Tue, 26 Jun 2018 11:12:56 +0000 http://ahex.wpenginepowered.com/?p=2233 What is Test Driven Development (TDD) ? Test Driven Development or TDD is a type of software development process where testing starts before writing any code. As the name suggests, in this process it is the “tests” that drives the “development” process. This approach helps a developer to create a detailed layout of what is...

The post Test Driven Development Using Laravel appeared first on Welcome to Ahex Technologies.

]]>
What is Test Driven Development (TDD) ?

Test Driven Development or TDD is a type of software development process where testing starts before writing any code. As the name suggests, in this process it is the “tests” that drives the “development” process. This approach helps a developer to create a detailed layout of what is expected from the code before they even start writing a single line of code. This helps in reducing bugs in short term and, due to automated nature of it, reduces lot of time in regression testing in long term.

TDD in Laravel

Laravel by default provides support for testing using PHPUnit. We are using Laravel 5.6 for this tutorial. Please refer to official docs to get a good understanding of the testing features provided by Laravel. Lets start with writing our first test.

Lets Start the TDD

I am assuming that you have already installed the Laravel. If not please visit official site here to install the Laravel. Once you are done with installation, create a new project using the command:

laravel new learn_tdd

This command will create a new Laravel project learn_tdd. Your project structure will be same as below.

In the project root directory, open the file phpunit.xml, which contains the phpunit configuration for your project. Your phpunit.xml file will be looking like this:


<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>

During the testing we may have to connect to database or may perform some operations in which database is required. We use sqlite with in memory option, as it is faster and DB is created during the testing process and destroyed in the end. I am adding those options to my phpunit.xml file.


<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>

Lets run our first round of test to check that after making changes in the phpunit.xml file, the default tests are running.

So, everything is working fine. Now lets do some test driven development. We are going to create a user registration system using this approach. Let’s begin.

Firstly let us think about the flow of the user registration in perspective with the backend of the system. Breaking that into steps:

Basic steps:

  1. User submits request for registration with the information that is required for registration.
  2. Validate the user submitted data.
  3. Store the information into the database.
  4. Return success status.

Alternative steps:

  1. System validation failed.
  2. System returns the error status with appropriate validation message.

To create our first test class lets use this command:

php artisan make:test UserRegistrationTest

This will create a new file named UserRegistrationTest in the test/Feature folder, containing a default method testExample(), which is auto-generated by artisan while creating the test class for us. The generated file will look like this:

namespace TestsFeature;

use TestsTestCase;
use IlluminateFoundationTestingWithFaker;
use IlluminateFoundationTestingRefreshDatabase;

class UserRegistrationTest extends TestCase
{
    use RefreshDatabase;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

Lets write our test by keeping in mind how our users are going to interact with the system. A user fills the the registration form with the required information and then submits it and waits for system to confirm his registration. Mapping these steps to our test class:

<?php

namespace TestsFeature;

use TestsTestCase;
use IlluminateFoundationTestingWithFaker;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateHttpResponse;

class UserRegistrationTest extends TestCase
{
    use RefreshDatabase;
    /**
     * 
     * @test
     */
    public function a_user_can_register()
    {
        //user fills the form
        $user = [
                'email' => 'test@mail.com',
                'name' => 'Test Name',
                'password' => '12345678',
        ];

        //user submits the form

        $this->json('post', 'api/register', $user)
            ->assertStatus(Response::HTTP_CREATED);
    }
}

In the a_user_can_register( ) method, we are first creating an array to simulate the step of user filling the form. The json( ) method simulates the user submission of the form with the data. We are using POST method as per REST architecture convention, since the data is going to written in the application database (To know more details on this read about REST calls How to build RESTful API using Lavavel 5.6 with Mysql). Once request has been submitted, system assert that we are going to receive a status of 201 from the system.

Please keep in mind, that for phpunit to execute a method as test, we either need to prefix the method name with test or we can add @test in the comment. I am using the later convention, you can use whatever you want or fits your coding policy.

Lets run this test and see what is the result:


 learn_tdd$ vendor/bin/phpunit

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.

 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✖  
 ==> TestsUnitExampleTest                       ✓  

Time: 191 ms, Memory: 14.00MB

There was 1 failure:

1) TestsFeatureUserRegistrationTest::a_user_can_register
Expected status code 201 but received 404.
Failed asserting that false is true.

/learn_tdd/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:109
/learn_tdd/tests/Feature/UserRegistrationTest.php:29

Oh! our first test failed, but this is what we were expecting. If we closely examine our failure message, it says that we got status message as 404 instead of the 201, which is no surprise, as we have not defined the route. Remember, we are following TDD here, where, test will drive the development and not the other way around. So lets define the route in the routes/api.php file.

Route::post('register', 'RegistrationController@store');

Now lets us run the test again and see whether our test pass or not:

learn_tdd$ vendor/bin/phpunit

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.

 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✖  
 ==> TestsUnitExampleTest                       ✓  

Time: 374 ms, Memory: 14.00MB

There was 1 failure:

1) TestsFeatureUserRegistrationTest::a_user_can_register
Expected status code 201 but received 500.
Failed asserting that false is true.

/learn_tdd/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:109
/learn_tdd/tests/Feature/UserRegistrationTest.php:29

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

Surprise! Our test failed again. Let us check the message we got this time. Now we are getting status code of 500 instead of 200, which means there is some internal server error. If we will go back to our routes/api.php file, we can see that we are routing the register request to RegistrationController, but there is no such controller. Let’s create the controller using the this command:

learn_tdd$ php artisan make:controller RegistrationController --resource

This will create RegistrationController in the appHttpControllers directory, auto generated with the methods to handle the REST based request. Lets run the test again,

learn_tdd$ vendor/bin/phpunit                                           

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.


 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✖  
 ==> TestsUnitExampleTest                       ✓  

Time: 276 ms, Memory: 14.00MB

There was 1 failure:

1) TestsFeatureUserRegistrationTest::a_user_can_register
Expected status code 201 but received 200.
Failed asserting that false is true.

/learn_tdd/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:109
/learn_tdd/tests/Feature/UserRegistrationTest.php:29

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

It failed again. It was expecting status code 201 but instead it is receiving 200 due to which the test failed. Ok, now let us save the user information into the database and return the appropriate response from our RegistrationController class.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppUser;
use IlluminateSupportFacadesHash;
use IlluminateHttpResponse;

class RegistrationController extends Controller
{
    //..... this part of the code is removed for display purpose

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        
        $user = new User();
        
        //initializing the value
        $user->email = $request->email;
        $user->name = $request->name;
        $user->password = Hash::make($request->password);
        
        //saving the value
        $user->save();
        
        return response([], Response::HTTP_CREATED);
    }

    //..... this part of the code is removed for display purpose
}

Here in the method store( ), we are saving the user submitted data in the database and then returning the 201 response, as per standard HTTP response code for creating a new resource. Now lets run the test again:

➜  learn_tdd$ vendor/bin/phpunit

PHPUnit 7.1.5 by Sebastian Bergmann and contributors.


 ==> TestsFeatureExampleTest                    ✓  
 ==> TestsFeatureUserRegistrationTest           ✓  
 ==> TestsUnitExampleTest                       ✓  

Time: 255 ms, Memory: 18.00MB

OK (3 tests, 3 assertions)

Great! Our test has passed and along with our feature of registering the user details. So, if you followed the steps, we have created one feature using the TDD methodology.  Happy Coding.

Note: We have not covered other features such as factories, validation and there is also some scope of improving the code structure. We will cover those in next few blogs one by one by improving upon what we have done here.

The post Test Driven Development Using Laravel appeared first on Welcome to Ahex Technologies.

]]>
2233
SEND SMS USING TWILIO AND LARAVEL https://ahex.co/send-sms-using-twilio-and-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=send-sms-using-twilio-and-laravel Wed, 21 Feb 2018 14:17:54 +0000 http://ahex.wpenginepowered.com/?p=2041 SMS messaging is one of the  most popular way of notifying user about otp, promotional offers and many other updates. In one of my project, there was requirement of sending otp to user’s phone device  and I had to develop web service for web and mobile apps to consume it for sending sms and that...

The post SEND SMS USING TWILIO AND LARAVEL appeared first on Welcome to Ahex Technologies.

]]>
SMS messaging is one of the  most popular way of notifying user about otp, promotional offers and many other updates. In one of my project, there was requirement of sending otp to user’s phone device  and I had to develop web service for web and mobile apps to consume it for sending sms and that is when I stumbled upon Twilio and how by using it with Laravel will give you the result with maximum efficiency and minimum amount of hard work.

In just a matter of few minutes and few lines of code you will be ready to send your first text message. To send a message, just make an HTTP POST to Twilio with the body of the message and the phone number you want to send it to.

Here we will cover the installation and integration of twilio in our project and then use it’s API to send SMS or OTP to a user. Follow the below given steps and then you are good to go. But,before going into the coding part, first let us learn about what twilio is and how does it work?

WHAT IS TWILIO

It is a cloud communication platform as a service. It allows software developer to programmatically make and receive phone calls and send and receive text messages using its web service APIs.This enables businesses to provide the right communications experience for their customers.

Behind Twilio API is a Super Network, a software layer that connects and optimizes communications networks around the world. This is what allows your users to reliably call and message anyone anywhere.Twilio uses Amazon Web Services to host telephony infrastructure and provide connectivity between HTTP and the public switched telephone network (PSTN) through its APIs.

With Twilio, you can reach customers in the ways they prefer, and engage with them effectively using context related to that interaction. As customer experience can increasingly make or break your brand, programmable communications has become more crucial than ever to the success of businesses today.

Sending an SMS or MMS is one of the most common tasks performed on the Twilio Platform. It requires AccountSID and AuthToken, they can be generated by registrting at Twilio.

Getting a Twilio SMS Account:
Here is a link to create an account on twilio if you don’t have one already.

After registration click on Account, there you will be able to see authsid and authtoken. You have assigned a sender mobile number which can be found at Twilio, which is used to send Text Messages or MMS and ShortCodes etc.

Sample Snapshot:

Capture

HOW DOES TWILIO WORK

When you send an SMS/MMS from your web app using Twilio it works like this:

sms-1-way

As you can see sending an SMS is pretty straight forward, and all of this interaction is triggered with just those few lines of code which we will see later.

INSTALLATION:

  • Download package form https://github.com/lakshmaji/twilio
  • OR to install with composer run the following command in your terminal
       composer require lakshmaji/twilio
       Composer dump-autoload
       Composer update

LARAVEL INTEGRATION:

First, you need to add the service provider. Open app/config/app.php, and add a new item to the providers array.

Lakshmaji\Twilio\TwilioServiceProvider::class,

Then, add a Facade for more convenient usage. In app/config/app.php add the following line to the aliases array:

'Twilio' => Lakshmaji\Twilio\Facade\Twilio::class,

Again do composer update again

After completing the above two steps, now open you terminal and create a controller called TwilioTestController. In this controller class we write an example code to send an otp to a user mobile.

Run the below command to create the controller class:

php artisan make:controller  TwilioTestController

Now, go to your TwilioTestController class and write down the below code.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Twilio; 

class TwilioTest extends Controller
{
  public function testMesssage()
  {

    // initialize message array 
    $message_array = array(
        'sender_id'     => 'TWILIO_USER_ID',
        'sender_secret' => 'TWILIO_USER_PASSWORD',
        'receiver_mobile' => '99999999999',
        'otp'     =>'325456',
        'sender' => 'TWILIO_SOURCE_MOBILE_NUMBER'
    );

    // This will send OTP only
    $sms_response = Twilio::message($message_array,$op="otp only", false, true,  false ); // otp

    return response()->json($sms_response,200);
  }
}

After writing the above code in your controller, go to route folder of your project and give the following route in your api.php file.

Route:: post(‘send_sms’,’TwilioTestController@testMessage’);

when you hit the above api, you will get the following Response:

Response Data:

{
   "account_sid": "AC6779d4499d13507f580f37e112a486a2",
   "api_version": "2010-04-01",
   "body": "325456",
   "num_segments": "1",
   "num_media": "1",
   "date_created": "Wed, 18 Aug 2010 20:01:40 +0000",
   "date_sent": null,
   "date_updated": "Wed, 18 Aug 2010 20:01:40 +0000",
   "direction": "outbound-api",
   "error_code": null,
   "error_message": null,
   "from": "+14158141829",
   "price": null,
   "sid": "MM90c6fc909d8504d45ecdb3a3d5b3556e",
   "status": "queued",
   "to": "+15558675310",
   "uri": "/2010-0401/Accounts/AC6779d4499d13507f580f37e112a486a2/Messages/MM90c6fc909d8504d45ecdb3a3d5b3556e.json"
}

NOTE:Trial accounts cannot send messages to unverified numbers; verify +9199XXX23867 at twilio.com/user/account/phone-numbers/verified, or purchase a Twilio number to send messages to unverified numbers.

By developing and consuming api we desicussed above, now you are able to add SMS capabilities to any of your web/mobile apps in minutes.Well I hope this taste of the Twilio API has left you excited to learn even more. To know more about twilio and it’s features visit https://www.twilio.com/. It is fully stocked with examples to help you dive in.

The post SEND SMS USING TWILIO AND LARAVEL appeared first on Welcome to Ahex Technologies.

]]>
2041
How To Send SMS Using Plivo and Laravel https://ahex.co/how-to-send-sms-using-plivo-and-laravel/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-send-sms-using-plivo-and-laravel Sat, 30 Dec 2017 06:00:00 +0000 http://ahex.wpenginepowered.com/?p=1602 Short Message Service (SMS) is a text messaging service component of most telephone, World Wide Web, and mobile device systems. It has achieved huge success in the wireless world. Billions of SMS messages are sent every day. SMS is now a major revenue generator for wireless carriers. A lot of innovative applications are now built...

The post How To Send SMS Using Plivo and Laravel appeared first on Welcome to Ahex Technologies.

]]>
Short Message Service (SMS) is a text messaging service component of most telephone, World Wide Web, and mobile device systems. It has achieved huge success in the wireless world. Billions of SMS messages are sent every day. SMS is now a major revenue generator for wireless carriers. A lot of innovative applications are now built on top of the SMS technology and more are being developed. Many people are turning to short messaging service or SMS messaging as a way to communicate with other individuals instead of making phone calls.

While working on one of the applications being developed on the Laravel framework, I came across a situation where I had to send OTP on user’s mobile phone to verify user mobile number. This could easily be done using plivo. This package enables to send any kind of message to any mobile. So, this blog will provide you information about how to send SMS to any mobile device.

WHAT IS PLIVO

  • Plivo is a Cloud API Platform and a Global Carrier Services Provider for Voice Calls and SMS.
  • Their mission is to simplify global telecom and enable access to quality cloud communications at a low cost. This means that you can add voice calling and SMS text messaging capabilities to any web or mobile app with just a few lines of code.
  • This uses Plivo! API.
  • It requires AuthId and AuthToken, they can be generated by registering @at Plivo after registrion click on Dashboard ,there you will be able to see authid and authtoken.

sample snapshot:
picture

INSTALLATION

To install this package you will need:

  • Laravel 4 or 5
  • PHP

To install via composer run the following command from the terminal.

  • composer require lakshmaji/plivo

LARAVEL INTEGRATION

Once this has finished, you will need to add the service provider to the providers array in your app.php config as follows:

  • LakshmajiPlivoPlivoServiceProvider::class,

Next, also in the app.php config file, under the aliases array, you are required to add the Plivo facade.

  • ‘plivo’ => LakshmajiPlivoFacadePlivo::class,

Finally, you will want to publish the config using the following command:

  • php artisan vendor:publish

In the plivo.php configuration file we need to enter the Plivo API key and ID.

sample snapshot:

Capture

NOTE : Don’t forget to set a auth id and auth secret keys in the config file!, you can get them at Plivo dashboard.

EXAMPLE CODE TO SEND SMS IN PHP

require 'vendor/autoload.php';
use PlivoRestAPI;
$auth_id = "Your AUTH_ID";
$auth_token = "Your AUTH_TOKEN";

$p = new RestAPI($auth_id, $auth_token);

// Set message parameters
$params = array(
        'src' => '1111111111', // Sender's phone number with country code
        'dst' => '2222222222', // Receiver's phone number with country code
        'text' => 'Hi, Message from Plivo', // Your SMS text message
        'url' => 'http://example.com/report/', // The URL to which with the status
          of the message is sent
        'method' => 'POST' // The method used to call the url
       );
// Send message
$response = $p->send_message($params);

// Print the response
echo "Response : ";
print_r ($response['response']);

// Print the Api ID
echo " Api ID : {$response['response']['api_id']}";

// Print the Message UUID
echo "Message UUID : {$response['response']['message_uuid'][0]}";

EXAMPLE CODE TO SEND SMS IN LARAVEL USING CURL

use Plivo;    
public function sendSms()
{    
    $auth_id = "Your AUTH_ID";
    $auth_token = "Your AUTH_TOKEN";

    $src = '1111111111'; //Sender's phone number with country code
    $des = '2222222222'; // Receiver's phone number with country code
    $text = 'Hi, Message from Plivo'; // Your SMS text message
    
    $url = 'http://example.com/report/'; // The URL to which with the status of
           the message is sent
    $data_sms = array("src" => "$src", "dst" => "$dst", "text" => "$text");
    $data_string = json_encode($data_sms);

        $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt(   $ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_USERPWD, $AUTH_ID . ":" . $AUTH_TOKEN);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        if(!$response){
           die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
          }

        $arr = json_decode($response, true );
        return $arr;

}

The post How To Send SMS Using Plivo and Laravel appeared first on Welcome to Ahex Technologies.

]]>
1602