twilio-php SDK Documentation

repository·main·Indexed 23 days ago

https://github.com/twilio/twilio-php

The official PHP SDK for interacting with the Twilio REST API. It allows developers to programmatically manage communications such as SMS and calls. The library supports PHP versions 7.2 through 8.4 and provides tools for generating TwiML responses, managing JWT AccessTokens and ClientTokens, and implementing custom HttpClients for proxy support. It includes built-in handling for API pagination via read(), stream(), and page() methods.

Tokens
9.5K
Snippets
22
Records
64
Agent score
82%

What's inside twilio-php

  1. Identify supported versions of twilio-php

    main
    Twilio only provides support for the current MAJOR version of the twilio-php library. All new features, functionality, bug fixes, and security updates are exclusively applied to the current major version. If you are using an older major version, you will not receive updates or security patches.
  2. Understand the twilio-php versioning strategy

    main

    The twilio-php library follows a modified Semantic Versioning (MAJOR.MINOR.PATCH) system. To ensure stability, it is strongly recommended to pin your dependency to at least a specific major version, and ideally a specific minor version, to prevent unexpected breaking changes during updates.

    • PATCH (MAJOR.MINOR.PATCH): Incremented for backwards-compatible bug fixes. These are generally safe to upgrade.
    • MINOR (MAJOR.MINOR.PATCH): Incremented when new features are added or small, backwards-incompatible changes (like function signature changes) are introduced. Upgrading may require manual code adjustments.
    • MAJOR (MAJOR.MINOR.PATCH): Incremented for significant breaking changes that require extensive code reworking. These are communicated in advance via Release Candidates.
  3. How paging and iteration work in twilio-php

    main

    The library automatically handles pagination for collections like calls and messages. You can interact with these collections in three ways:

    1. read(): Eagerly fetches all records matching your criteria and returns them as a list.
    2. stream(): Returns an iterator that lazily retrieves pages of records as you iterate, which is more memory-efficient for large datasets.
    3. page(): Allows manual pagination by retrieving a single page of results. You can then use nextPage() on the returned page object to get the subsequent page.

    You can control the number of records returned using limit and the size of each page using pageSize.

    <?php
    require_once '/path/to/vendor/autoload.php';
    
    $sid = "ACXXXXXX";
    $token = "YYYYYY";
    $client = new Twilio\Rest\Client($sid, $token);
    
    $limit = 5;
    $pageSize = 2;
    
    // Read - fetches all messages eagerly and returns as a list
    $messageList = $client->messages->read([], $limit);
    foreach ($messageList as $msg) {
        print($msg->sid);
    }
    
    // Stream - returns an iterator of 'pageSize' messages at a time and lazily retrieves pages until 'limit' messages
    $messageStream = $client->messages->stream([], $limit, $pageSize);
    foreach ($messageStream as $msg) {
        print($msg->sid);
    }
    
    // Page - get the a single page by passing pageSize, pageToken and pageNumber
    $messagePage = $client->messages->page([], $pageSize);
    $nextPageData = $messagePage->nextPage();  // this will return data of next page
    foreach ($messagePage as $msg) {
        print($msg->sid);
    }
  4. Implement a custom HttpClient for proxy support

    main

    To create a custom HTTP client, extend Twilio\\/Http\\/CurlClient and override the request method. This allows you to intercept the request parameters and apply custom logic, such as setting CURLOPT_PROXY or CURLOPT_CAINFO.

    When implementing request, you should:

    1. Use $this->options(...) to retrieve the standard request parameters.
    2. Initialize cURL and apply the options.
    3. Apply your custom logic (e.g., proxy settings).
    4. Execute the request and parse the response into a Twilio\\/Http\\/Response object containing the status code, body, and headers.
    use Twilio\/Http\\/CurlClient;
    use Twilio\/Http\\/Response;
    
    class MyRequestClass extends CurlClient
    {
        protected $http = null;
        protected $proxy = null;
    
        public function __
    {...}
    
        public function request(
            $method,
            $url,
            $params = array(), $data = array(), $headers = array(), $user = null, $password = null, $timeout = null): Response
        {
            // Implementation logic here
        }
    }
  5. Upgrade to Twilio PHP Helper Library 8.x.x

    main

    Version 8.0.0 is a major release. It is designed to be a drop-in replacement without breaking changes to existing APIs.

    Key improvements:

    • The library is now auto-generated via OpenAPI, ensuring faster feature additions and cross-language consistency.
    • Added support for the application/json content type in request bodies.
  6. PHP Version Compatibility (6.x.x)

    main
    Version 6.x.x officially dropped support for PHP versions 5.5, 5.6, 7.0, and 7.1. This release introduced scalar parameter type declarations and return types, which may cause a TypeError if incompatible types are passed to library functions.
  7. Upgrade to Twilio PHP Helper Library 7.x.x

    main

    Version 7.0.1 is a major release. It is designed to be a drop-in replacement without breaking changes to existing APIs.

    Key improvements:

    • The library is now auto-generated via OpenAPI, ensuring faster feature additions and cross-language consistency.
  8. Install the Twilio PHP SDK without Composer

    main

    If you cannot use a package manager, you can download the full source from GitHub and unzip it into your project directory. To use it, you must manually require the bundled autoload.php file located within the SDK directory.

    <?php
    // Require the bundled autoload file - the path may need to change
    // based on where you downloaded and unzipped the SDK
    require __DIR__ . '/twilio-php-main/src/Twilio/autoload.php';
    
    // Your Account SID and Auth Token from console.twilio.com
    $sid = "ACXXXXXX";
    $token = "YYYYYY";
    $client = new Twilio\Rest\Client($sid, $token);
    
    // Use the Client to make requests to the Twilio REST API
    $client->messages->create(
        // The number you'd like to send the message to
        '+15558675309',
        [
            // A Twilio phone number you purchased at https://console.twilio.com
            'from' => '+15017250604',
            // The body of the text message you'd like to send
            'body' => "Hey Jenny! Good luck on the bar exam!"
        ]
    );
  9. Handle Twilio exceptions

    main

    The library throws specific exceptions that you should catch to prevent application crashes:

    • Twilio\Exceptions\ConfigurationException: Thrown during client initialization (e.g., invalid credentials).
    • Twilio\Exceptions\EnvironmentException: Thrown if required system dependencies (like curl) are missing.
    • Twilio\Exceptions\TwilioException: The most common exception, thrown when an API request fails.
    • Twilio\Exceptions\TwimlException: Thrown when generated TwiML does not conform to API expectations.
    <?php
    require_once('/path/to/twilio-php/Services/Twilio.php');
    
    use Twilio\Exceptions\TwilioException;
    use Twilio\Rest\Client;
    
    $sid = "ACXXXXXX";
    $token = "YYYYYY";
    $client = new Twilio\Rest\Client($sid, $token);
    
    try {
        $call = $client->account->calls
            ->get("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    } catch (TwilioException $e) {
        print $e->getCode();
    }
    
    print $call->to;
  10. Configure proxy settings via environment variables

    main

    When using a custom HTTP client to route traffic through a proxy, it is recommended to store your proxy address in an environment variable. The proxy address should be in IP:Port format.

    Example .env configuration:

    ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    AUTH_TOKEN=your_auth_token
    PROXY=127.0.0.1:8888
    ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    AUTH_TOKEN= your_auth_token
    
    PROXY=127.0.0.1:8888
  11. Make a phone call

    main

    Use the Twilio\Rest\Client to initiate an outbound call. You must provide a url in the options array that points to valid TwiML instructions for the call to execute when it connects.

    <?php
    $sid = "ACXXXXXX";
    $token = "YYYYYY";
    
    $client = new Twilio\Rest\Client($sid, $token);
    
    // Read TwiML at this URL when a call connects (hold music)
    $call = $client->calls->create(
        '8881231234',
        // Call this number
        '9991231234',
        // From a valid Twilio number
        [
            'url' => 'https://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient'
        ]
    );