メニュー

Expand
ページを評価:

Twilio SMS PHP クイックスタート

Ahoy there! All messaging transmitted using Twilio’s messaging channels is treated as Application-to-Person (A2P) messaging and subject to Twilio’s Messaging Policy. For detailed information on policy rules to ensure you remain compliant while using Twilio’s services, please see our Acceptable Use Policy.

In a few lines of code, your PHP application can send, receive, and reply to text messages with Twilio Programmable SMS.

This PHP SMS Quickstart shows you how to use our Communications REST API, the Twilio CLI, and the Twilio PHP helper library.

We’ll use the package manager Composer to manage our product dependencies. If you don’t want to use Composer, no problem — we also have a separate non-Composer PHP SMS Quickstart.

In this Quickstart, you’ll learn how to:

  1. Sign up for Twilio and purchase an SMS-enabled phone number.
  2. Check and install any prerequisites using Composer.
  3. Send your first SMS.
  4. Set up your development environment to send and receive messages.
  5. Receive inbound text messages.
  6. Reply to incoming messages with a return SMS.
I'm in. Show me how!

Sign up — or into — Twilio

Already have a Twilio account? Go ahead and skip this section.

You can sign up for a free Twilio trial account here.

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked a series of questions to customize your experience.
  • Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.
I've got an account! What's next?

Install the Twilio CLI

We’ll need to use the Twilio CLI (command line interface) for a few tasks, so let’s install that now.

One of the easiest ways to install the CLI on macOS is to use Homebrew. If you don't already have it installed, visit the Homebrew site for installation instructions and then return here.

Once Homebrew is installed, simply run the following command to install the CLI:

brew tap twilio/brew && brew install twilio

Updating

If you already installed the CLI with brew and want to upgrade to the latest version, run:

brew upgrade twilio

Warning for Node.js developers

If you have installed Node.js version 10.12 or higher on your Mac, you can avoid potential Node.js version conflicts by installing the CLI using npm:

npm install twilio-cli -g

はじめる前に

Before we can install, we need to make sure you have Node.js installed (version 12.21 or above). To see if you have node installed, try running this command:

node -v

If your system reports v12.21 or above, you can skip the next step.

Installing Node.js on Windows

Using the Windows Installer (.msi) is the recommended way to install Node.js on Windows. You can download the installer from the Node.js download page.

Run PowerShell as an administrator, and type the following command:

Set-ExecutionPolicy Bypass -Scope Process

You should see the following output:

Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"):

Enter Y to confirm the change.

Note you will have to set this execution policy every time you run PowerShell. See notes on Set-ExecutionPolicy to learn more.

Tested Windows Versions

These instructions have been tested on the following Windows versions:

  • Windows 10 Pro
  • Windows Server 2016

Installing Twilio CLI

The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:

npm install twilio-cli -g

Note the -g option is what installs the command globally so you can run it from anywhere in your system.

Updating

If you already installed the CLI with npm and want to upgrade to the latest version, run:

npm install twilio-cli@latest -g

Before we can install, we need to make sure you have Node.js installed (version 10.12 or above). Even if you already installed Node yourself, the CLI works best when you install it using nvm. Here's how to get nvm installed on most Linux systems:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash

Please visit the nvm installation instructions for additional options and troubleshooting steps. Once you have nvm installed, run the following to install and use the most recent LTS release of Node.js:

nvm install --lts
nvm use <insert version reported from above>

Installing other Twilio CLI prerequisites for Linux

Depending on your distribution, you will need to run one of the following commands:

  • Debian/Ubuntu: sudo apt-get install libsecret-1-dev
  • Red Hat-based: sudo yum install libsecret-devel
  • Arch Linux: sudo pacman -S libsecret

Installing Twilio CLI

The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:

npm install twilio-cli -g

Note the -g option is what installs the command globally so you can run it from anywhere in your system.

Updating

If you already installed the CLI with npm and want to upgrade to the latest version, run:

npm install twilio-cli@latest -g

Run twilio login to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to provide to the CLI.

認証トークンは、目玉アイコンをクリックすると表示されます:

認証トークンを表示する

Now to get a phone number...

Get a phone number

If you don’t currently own a Twilio phone number with SMS functionality, you’ll need to purchase one. With the CLI, run:

twilio phone-numbers:buy:local --country-code US --sms-enabled

Replace US with your ISO-3166-1 country code if you would like a phone number in another country. If you aren’t being presented with any SMS-enabled numbers, try looking for a mobile number instead of a local number: twilio phone-numbers:buy:mobile --country-code DE --sms-enabled

Select a phone number to add it to your account.

Next, we need to install PHP and the Twilio PHP Helper Library.

素晴らしそう! インストール方法を教えてください。

PHPとTwilio PHPヘルパーライブラリーをインストールする

If you already have PHP and the Twilio PHP Helper Library installed in your working directory, feel free to skip this step and move on to sending your first text message.

To send your first SMS, let's make sure you’re set up with PHP and able to install Twilio’s PHP Helper library. When doing web development in PHP, we strongly suggest using Composer for package management. This Quickstart relies on Composer to install the PHP Helper library. If you choose not to use Composer, please visit our non-Composer PHP SMS Quickstart.

PHPをインストールする

MacまたはLinux、Unixマシーンをお使いの場合、PHPはすでにインストールされている可能性があります。 使い慣れたターミナルで下記を実行します:

php --version

インストールされていない場合は、PHPのインストール手順に従ってください。

If you’re using a Windows machine, please follow the official PHP tutorial to install PHP.

While many versions of PHP 5.x and PHP 7.x will work for this Quickstart, please pay attention to supported PHP releases. Always update un-supported versions when doing web development, as older versions will not receive security updates.

Composerをインストールする

Composer is the de facto standard package manager for PHP web development. If you haven’t yet installed it, here are the installation instructions for your platform:

If you’d prefer to install dependencies manually, check out our non-Composer PHP SMS Quickstart.

PHPヘルパーライブラリをインストールする

We need to install the Twilio PHP Helper Library in the directory where you will complete the Quickstart. If you are using Composer, there are two ways to do this.

第一の方法はターミナルを使用して、下記のコマンドを実行することです:

composer require twilio/sdk

Alternatively, you can create a file named composer.json and then add the following to it:

{
    "require": {
        "twilio/sdk": "^5.0"
    }
}

そして、下記を実行します

composer install

And composer will grab the latest version of the Twilio PHP Helper Library.

Finally, for a non-composer installation follow the instructions here. You’ll also need to change the code samples as they appear in this Quickstart as shown in those instructions.

Prerequisites are done! Let's send an SMS.

PHPでSMSを送信する

これでPHP、Composer、そしてtwilio-phpのインストールが済んだので、APIリクエストをひとつ送信して、Twilio電話番号からテキストメッセージを送信できます。 send_sms.phpという名前のファイルを作成して開き、下記のコードサンプルを入力またはペースとします。

        
        
        
        アカウントSID、認証トークンを編集し、Twilio番号をSMS機能を持ったTwilio電話番号に変更し、PHPを使用してSMSを送信できるようにします(日本のTwilio電話番号はSMS機能に対応しておりませんのでご注意ください。 別途米国(+1)の番号をご購入ください)。

        PHPでSMSを送信する

        アカウントSID、認証トークンを編集し、Twilio番号をSMS機能を持ったTwilio電話番号に変更し、PHPを使用してSMSを送信できるようにします(日本のTwilio電話番号はSMS機能に対応しておりませんのでご注意ください。 別途米国(+1)の番号をご購入ください)。

        プレースホルダーのTwilioクレデンシャルを置き換える

        Swap the placeholders in account_sid and auth_token with your personal Twilio credentials. Replace the values for account_sid and auth_token with your unique values.

        While it’s easier to hardcode your credentials in a file for this quickstart, you should use environment variables to keep them secret in production. Check out how to set environment variables for more information, and see the code comments for an example of how to read them in PHP. This repo is also an excellent resource for dealing with environment variables.

        twilio_numberの電話番号を置き換える

        Earlier, you purchased an SMS-enabled phone number. Paste that number into the twilio_number variable using E.164 formatting:

        [+][country code][phone number including area code]

        Replace the ‘To’ number in the create() call

        The first value in the call to create() is the outgoing phone number, currently set to +15558675310. This can be any phone number that can receive text messages, but you should use a number you control first to witness the magic! As above, use E.164 formatting for this number.

        ファイルを保存してスクリプトを実行します:

        php send_sms.php

        じゃーん! すべての値が正しいなら、Twilio番号からお手持ちの電話にSMSが受信されていることでしょう。

        Are your customers in the US or Canada? You can also send them MMS messages by adding just one line of code. Check out this guide to sending MMS to see how to do it.

        If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console’s Verified Caller IDs.

        プログラムでSMSが届くなんて魔法みたいだ! さて、お次は?

        PHPでSMSを受信、返信する

        When someone sends an SMS to your Twilio phone number, Twilio makes an HTTP POST request to your server asking for instructions on what to do next. For this Quickstart, we’ll reply to the sender with a note about how we're sending our SMS reply.

        We’ll again use the Twilio PHP Library, then use PHP’s built-in development webserver in combination with ngrok to instruct Twilio how to handle the message. Create a new file reply_sms.php in the same directory as send_sms.php, open it, then copy and paste or type the following code.

        If you’re not using the same directory as before, please follow the PHP Helper Library install step above.

              
              
              
              Twilio PHPヘルパーライブラリーを使用してSMSを受信し、アプリケーションからそれに返信を行う方法をデモンストレーションします。

              PHPでSMSを受信、返信する

              Twilio PHPヘルパーライブラリーを使用してSMSを受信し、アプリケーションからそれに返信を行う方法をデモンストレーションします。

              ファイルを保存し、下記のコマンドでPHPの開発用サーバーを開始します:

              php -S localhost:8000

              使い慣れたブラウザーで、 http://localhost:8000/reply_sms.php にアクセスします。

              If all went well, you should see TwiML in your browser with the message we’d like to reply with to all our inbound texts. And, yes, that’s all the code you need. But there’s just one more step you need to perform before everything is wired up.

              I'm getting excited now — let's connect our PHP to Twilio!

              WebhookのURLを設定する

              You need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:

              twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:8000/reply_sms.php"

              The CLI will start an ngrok tunnel — so Twilio can reach your development machine — and wait patiently for incoming text messages!

              SMSを送信しアプリケーションをテストする

              Now that everything is glued together, it’s time to test.

              Send a text message from your mobile phone to your Twilio phone number. You’ll see a couple of things happen very quickly:

              1. Your PHP dev server will note a new connection.
              2. TwilioはレスポンスをSMSとして転送します!
              It worked! All done — what's next?

              次のステップ

              Now that you know the basics of sending and receiving SMS and MMS text messages with PHP, you might want to check out these resources:

              We hope you enjoyed the quickstart, and definitely can’t wait to see what you build!

              ページを評価:

              ヘルプが必要ですか?

              We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.

                    
                    
                    

                    フィードバックくださりありがとうございます!

                    We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

                    Sending your feedback...
                    🎉 Thank you for your feedback!
                    Something went wrong. Please try again.

                    Thanks for your feedback!

                    Refer us and get $10 in 3 simple steps!

                    ステップ1

                    Get link

                    Get a free personal referral link here

                    ステップ2:

                    Give $10

                    Your user signs up and upgrade using link

                    ステップ3

                    Get $10

                    1,250 free SMSes
                    OR 1,000 free voice mins
                    OR 12,000 chats
                    OR more