Back to Blog
Language How-Tos

How to Send SMS from a Web App in Twilio Using PHP

Build a PHP web form that sends Twilio SMS on submission with input validation, credential security via environment variables, and error display.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
PHP
How-To
Code
How to Send SMS from a Web App in Twilio Using PHP

This tutorial builds a PHP web application with an HTML form that sends a Twilio SMS when a user submits a phone number and message, covering server-side input validation, secure credential management, and clear error feedback in the browser. It targets developers who want to give non-technical team members a browser-based interface for sending messages without direct API access. You will build a single PHP file that renders the form on GET requests and handles the SMS send on POST requests with proper validation and user feedback.

Prerequisites and Setup

Install the packages with composer require twilio/sdk vlucas/phpdotenv and load your Twilio credentials from a .env file that is never committed to version control. Validate the submitted phone number on the server with a regex before calling the Twilio API to give users a clear E.164 format error message instead of a raw Twilio exception. Never pass your Twilio Auth Token through a browser-side JavaScript variable or expose it in any HTML source; always keep it server-side in environment variables. Use htmlspecialchars() when echoing any user-submitted values back into the HTML response to prevent reflected cross-site scripting.

composer require twilio/sdk vlucas/phpdotenv

# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567

The Complete Code

The single PHP file checks $_SERVER['REQUEST_METHOD'] to branch between rendering the form on GET and processing the send on POST. Server-side validation with preg_match() confirms the phone is in E.164 format before any API call is made, returning a user-readable error message if the format is wrong. A try/catch block around $client->messages->create() catches any RestException and displays the error message to the user without exposing a stack trace. The success state displays the message SID so the user can reference it in the Twilio Console if needed.

<?php
require_once 'vendor/autoload.php';

use TwilioRestClient;
use TwilioExceptionsRestException;

$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();

$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone   = trim($_POST['phone']   ?? '');
    $message = trim($_POST['message'] ?? '');

    if (!preg_match('/^+[1-9]d{7,14}$/', $phone)) {
        $error = 'Phone must be in E.164 format, e.g. +15551234567';
    } elseif ($message === '') {
        $error = 'Message body cannot be empty.';
    } else {
        $client = new Client($_ENV['TWILIO_ACCOUNT_SID'], $_ENV['TWILIO_AUTH_TOKEN']);
        try {
            $msg     = $client->messages->create($phone, [
                'from' => $_ENV['TWILIO_PHONE_NUMBER'],
                'body' => $message,
            ]);
            $success = 'Message sent successfully. SID: ' . $msg->sid;
        } catch (RestException $e) {
            $error = 'Send failed: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html><head><title>Send SMS</title></head><body>
<h2>Send an SMS via Twilio</h2>
<?php if ($error):   ?><p style="color:red"><?php echo htmlspecialchars($error);   ?></p><?php endif; ?>
<?php if ($success): ?><p style="color:green"><?php echo htmlspecialchars($success); ?></p><?php endif; ?>
<form method="POST">
  <label>To (E.164 format):</label><br>
  <input type="tel" name="phone" placeholder="+15551234567" required /><br><br>
  <label>Message:</label><br>
  <textarea name="message" rows="4" cols="40" required></textarea><br><br>
  <button type="submit">Send SMS</button>
</form>
</body></html>

Testing and Debugging

Open the PHP page in a browser, enter a valid E.164 number, type a short message, and click Send SMS. A green success message with the SID should appear and the SMS should arrive on the destination phone within seconds. Test validation by submitting the form with the phone number missing the leading plus sign and confirm the red error message appears. On trial accounts test with a verified number first; submitting an unverified number produces a Twilio 21608 error that is caught and displayed as the red error message via $e->getMessage().

Taking It Further

Add a CSRF token to the form using PHP sessions: generate a random token on GET, store it in the session, embed it as a hidden field, and validate it matches on POST before processing the send. Implement per-session rate limiting by counting sends in a session variable and blocking submissions above a configured threshold per hour to prevent abuse. Log every send attempt to a database with the operator's session ID, destination number, message length, timestamp, and SID for audit and compliance purposes. Move the send logic into a dedicated SMS service class that wraps the Twilio client and inject it as a Laravel service so it can be tested with a mock client in unit tests without making real API calls.

Contact Telphi Consulting to build a secure internal PHP SMS tool with user management, audit logging, and delivery tracking for your team.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.