Fast2SMS
No library, no API fee

SMS API in PHP
with Sample Code

Send SMS and OTPs from your PHP website or app with one cURL request. Copy working code for plain PHP, Laravel, CodeIgniter and WordPress, then get delivery reports on a webhook. Pay only per SMS, from ₹0.25 down to ₹0.11.

  • Plain PHP, Laravel, CI4, WordPress
  • DLT, Quick SMS and OTP
  • Webhooks included
  • ₹50 free test credit
send-sms.phpPOST
<?php
$ch = curl_init('https://www.fast2sms.com/dev/bulkV2');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'authorization: ' . getenv('FAST2SMS_API_KEY'),
        'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode([
        'route' => 'dlt',
        'sender_id' => 'DEMOTR',
        'message' => '10001',
        'variables_values' => 'Rahul|DT10458',
        'numbers' => '9999999999',
    ]),
]);
echo curl_exec($ch);
"return": true · request_id Sa1B2c3D4e5F6g7
DEMOTRHi Rahul, your order DT10458 is confirmed. Demo Traders
1Endpoint for DLT and Quick SMS
₹0.11Lowest rate per SMS
0Libraries to install
7 daysOf API Logs in the panel
SMS API in PHP

How an SMS API works in PHP

An SMS API is a web address your PHP code calls to send a text message without anyone opening a panel. Your script sends the mobile numbers and the message details to Fast2SMS over HTTPS. Fast2SMS checks your key, your sender ID and your template, charges your wallet and passes the SMS to the operator. The reply comes back in under a second as JSON with a request_id you can save.

In PHP that is one cURL call, so you do not need an SMS gateway script, a Composer package or a GSM modem. The same request works from a contact form, a WooCommerce order hook, a Laravel job, a cron script or a CodeIgniter controller. Delivery results come later, either from the delivery report API or pushed to your own PHP script by a webhook.

This page walks through the full integration: the routes, every parameter, ready code for plain PHP and the popular frameworks, OTP login, bulk sends, Hindi text, delivery reports, errors and security. For the same requests in Python, Node.js, Java, C#, Go and Ruby, see the SMS API page, and for every endpoint see the API documentation.

Before you start

What you need before the first call

Most PHP developers send their first test SMS within an hour of signing up.

A Fast2SMS account and API key

Sign up, then open Account Setting and API Key under UTILITY. Switch on API Access, click View, enter the OTP sent to your account mobile and copy the key. The same key works for SMS, OTP, WhatsApp, RCS and voice.

DLT sender ID and template

For your own sender name, the entity, header and content template must be approved on a DLT portal and added in DLT Manager. Each template card shows a short Message ID; that is what the API needs, not the 19-digit DLT template ID. Our team helps with DLT for free.

Wallet balance

Recharge from ₹100. Your per-SMS rate depends on the recharge slab, from ₹0.25 down to ₹0.11. New accounts get ₹50 free credit to send real test messages.

A server running PHP

Call the API from your backend: plain PHP with the cURL extension, Laravel, CodeIgniter, WordPress or any framework. Never call it from browser JavaScript or a mobile app, because the key would be visible to everyone.

Routes

Pick the right SMS route

DLT and Quick SMS go to https://www.fast2sms.com/dev/bulkV2. Smart OTP has its own endpoints.

dlt

The template Message ID plus variable values.

  • Sender: Your own approved header
  • DLT registration: Yes
  • Best for: Order updates, alerts, reminders and OTPs from your brand name

dlt_manual

The full approved text with template_id and entity_id.

  • Sender: Your own approved header
  • DLT registration: Yes
  • Best for: Systems that already store DLT IDs and full text

q (Quick SMS)

Your own free text.

  • Sender: Random sender
  • DLT registration: No
  • Best for: Occasional business messages before DLT is ready

/dev/otp/send (Smart OTP)

Mobile number and OTP ID; Fast2SMS makes the code.

  • Sender: Your OTP template
  • DLT registration: Template needed
  • Best for: Login and signup codes with verify built in

Parameters for /dev/bulkV2

Send the key in the authorization header. The body can be JSON, form data or a GET query string.

ParameterRequiredRule
routeYesdlt, dlt_manual or q.
sender_iddlt routesOne of your approved sender IDs in DLT Manager, in exactly the same case.
messageYesroute dlt: the Message ID from DLT Manager. route q: your text (English or Unicode, detected automatically).
variables_valuesIf the template has variablesOne value per {#var#}, in order, separated by |. Each value is cut to 40 characters.
numbersYes10-digit Indian mobile numbers starting with 6 to 9, separated by commas. A leading 91 is removed.
schedule_timeNoSend later: a future time as DD-MM-YYYY-HH-MM (IST) or a Unix timestamp. Works on dlt, dlt_manual and q.
sms_detailsNo1 adds character count, SMS parts, rate, valid and invalid numbers and the amount to the reply.
udf1, udf2, udf3NoYour own reference, such as an order ID. Stored with the SMS and sent back in webhooks.
iNight hold for promotional SMS. If the template is Promotional or Service Explicit, or the sender is numeric, SMS sent outside roughly 10 AM to 9 PM are held and sent the next morning. Transactional (Service Implicit) templates go out at any time, which is what OTPs and order alerts need.
Plain PHP

Send your first SMS with PHP cURL

Replace DEMOTR, 10001 and the values with your own sender ID, Message ID and variables. Keep the key in an environment variable.

POST with JSON (recommended)POST
<?php
// send-sms.php: one DLT SMS with plain PHP and cURL
$apiKey = getenv('FAST2SMS_API_KEY');

$payload = [
    'route'            => 'dlt',
    'sender_id'        => 'DEMOTR',   // your approved header, same case
    'message'          => '10001',    // Message ID from DLT Manager
    'variables_values' => 'Rahul|DT10458',
    'numbers'          => '9999999999',
];

$ch = curl_init('https://www.fast2sms.com/dev/bulkV2');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => [
        'authorization: ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE),
]);
$body = curl_exec($ch);
$err  = curl_error($ch);
curl_close($ch);

if ($body === false) {
    exit('Network error: ' . $err);
}
$res = json_decode($body, true);
if (($res['return'] ?? false) === true) {
    echo 'Accepted, request_id ' . $res['request_id'];
} else {
    echo 'Refused: ' . ($res['status_code'] ?? '') . ' '
        . json_encode($res['message'] ?? '');
}
GET with http_build_queryGET
<?php
// the same send as a GET request
$query = http_build_query([
    'route'            => 'dlt',
    'sender_id'        => 'DEMOTR',
    'message'          => '10001',
    'variables_values' => 'Rahul|DT10458',
    'numbers'          => '9999999999,8888888888',
], '', '&', PHP_QUERY_RFC3986); // encodes spaces, | and Hindi

$ch = curl_init('https://www.fast2sms.com/dev/bulkV2?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => [
        'authorization: ' . getenv('FAST2SMS_API_KEY'),
    ],
]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($res);

/* Success:
{
  "return": true,
  "request_id": "Sa1B2c3D4e5F6g7",
  "message": ["SMS sent successfully."]
}
*/
iAlways read "return", not only the HTTP code. The message field is a list, and "SMS sent successfully." means the SMS was accepted and queued, not yet delivered. Other good replies are "SMS scheduled successfully." and "After approval, SMS will be sent." for Quick SMS held for a check.

A reusable PHP SMS class

Drop one file into any project. The rest of this page uses it for forms, OTPs, bulk sends and reports.

Fast2Sms.phpPHP 7.4+
<?php
// Fast2Sms.php: a small client for any PHP 7.4+ project
final class Fast2Sms
{
    private string $key;
    private string $base = 'https://www.fast2sms.com';

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    /** DLT SMS: Message ID + variables, one or many numbers */
    public function dlt(string $sender, string $messageId, array $vars,
                        array $numbers, array $extra = []): array
    {
        return $this->post('/dev/bulkV2', [
            'route'            => 'dlt',
            'sender_id'        => $sender,
            'message'          => $messageId,
            'variables_values' => implode('|', $vars),
            'numbers'          => implode(',', $numbers),
        ] + $extra);
    }

    /** Quick SMS: free text, no DLT */
    public function quick(string $text, array $numbers): array
    {
        return $this->post('/dev/bulkV2', [
            'route'   => 'q',
            'message' => $text,
            'numbers' => implode(',', $numbers),
        ]);
    }

    /** Delivery report for one request (last 7 days) */
    public function dlr(string $requestId): array
    {
        return $this->call('GET', '/dev/dlr/' . rawurlencode($requestId));
    }

    public function post(string $path, array $data): array
    {
        return $this->call('POST', $path, $data);
    }

    private function call(string $method, string $path, array $data = []): array
    {
        $ch = curl_init($this->base . $path);
        $opts = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTPHEADER     => [
                'authorization: ' . $this->key,
                'Content-Type: application/json',
            ],
        ];
        if ($method === 'POST') {
            $opts[CURLOPT_POST]       = true;
            $opts[CURLOPT_POSTFIELDS] = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        curl_setopt_array($ch, $opts);
        $body = curl_exec($ch);
        $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $json = is_string($body) ? json_decode($body, true) : null;
        $ok   = ($json['return'] ?? $json['success'] ?? false) === true;
        return ['http' => $http, 'ok' => $ok, 'data' => $json];
    }
}

// usage
$sms = new Fast2Sms(getenv('FAST2SMS_API_KEY'));
$r = $sms->dlt('DEMOTR', '10001', ['Rahul', 'DT10458'], ['9999999999'],
               ['udf1' => 'order-10458']);
echo $r['ok'] ? $r['data']['request_id'] : json_encode($r['data']);
Frameworks

Laravel, CodeIgniter 4 and WordPress

The same DLT request in the way each framework likes to make HTTP calls, plus a Laravel queue job.

Laravel (Http facade)
// .env
FAST2SMS_API_KEY=your_key_here

// config/services.php
'fast2sms' => ['key' => env('FAST2SMS_API_KEY')],

// app/Services/Sms.php
namespace App\Services;

use Illuminate\Support\Facades\Http;

class Sms
{
    public static function dlt(string $messageId, array $vars,
                               string $mobile): ?string
    {
        $res = Http::withHeaders([
                'authorization' => config('services.fast2sms.key'),
            ])
            ->timeout(30)
            ->post('https://www.fast2sms.com/dev/bulkV2', [
                'route'            => 'dlt',
                'sender_id'        => 'DEMOTR',
                'message'          => $messageId,
                'variables_values' => implode('|', $vars),
                'numbers'          => $mobile,
            ])->json();

        return ($res['return'] ?? false) === true
            ? $res['request_id'] : null;
    }
}
Laravel (queued job)
<?php
// app/Jobs/SendSms.php: send from the queue
namespace App\Jobs;

use App\Services\Sms;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendSms implements ShouldQueue
{
    use Dispatchable, Queueable;

    public int $tries = 1; // no blind retries

    public function __construct(
        public string $messageId,
        public array $vars,
        public string $mobile,
    ) {}

    public function handle(): void
    {
        Sms::dlt($this->messageId, $this->vars, $this->mobile);
    }
}

// in a controller, after the order is saved
SendSms::dispatch('10001', ['Rahul', 'DT10458'], '9999999999');
CodeIgniter 4 (CURLRequest)
<?php
// app/Libraries/Sms.php (CodeIgniter 4)
namespace App\Libraries;

class Sms
{
    public function dlt(string $messageId, string $vars,
                        string $mobile): array
    {
        $client = \Config\Services::curlrequest([
            'timeout' => 30,
        ]);
        $response = $client->post(
            'https://www.fast2sms.com/dev/bulkV2', [
            'headers' => [
                'authorization' => getenv('FAST2SMS_API_KEY'),
            ],
            'json' => [
                'route'            => 'dlt',
                'sender_id'        => 'DEMOTR',
                'message'          => $messageId,
                'variables_values' => $vars,
                'numbers'          => $mobile,
            ],
            'http_errors' => false,
        ]);
        return json_decode($response->getBody(), true) ?? [];
    }
}

// in a controller
$r = (new \App\Libraries\Sms())
    ->dlt('10001', 'Rahul|DT10458', '9999999999');
WordPress (wp_remote_post)
<?php
// in your plugin, or the theme's functions.php
// define('FAST2SMS_API_KEY', '...'); goes in wp-config.php
function demo_send_sms( $mobile, array $vars ) {
    $response = wp_remote_post(
        'https://www.fast2sms.com/dev/bulkV2', array(
        'timeout' => 30,
        'headers' => array(
            'authorization' => FAST2SMS_API_KEY,
            'Content-Type'  => 'application/json',
        ),
        'body' => wp_json_encode( array(
            'route'            => 'dlt',
            'sender_id'        => 'DEMOTR',
            'message'          => '10001',
            'variables_values' => implode( '|', $vars ),
            'numbers'          => $mobile,
        ) ),
    ) );
    if ( is_wp_error( $response ) ) {
        return false;
    }
    $res = json_decode(
        wp_remote_retrieve_body( $response ), true );
    return ( $res['return'] ?? false ) === true;
}

Laravel tips

Send SMS from a queued job so a slow network never holds up the web request, and keep the key in .env through config/services.php. The Http facade sends JSON by default.

CodeIgniter tips

Set http_errors to false so a 400 reply comes back as data you can read instead of an exception. Put the key in the .env file of the project, outside the public folder.

WordPress and WooCommerce

Define the key in wp-config.php. For order SMS and OTP login without code, the free WooCommerce SMS and WhatsApp plugin already does this for you.

Use case

Send an SMS when someone fills your website form

The most common first project: a visitor sends an enquiry, and a second later they get a thank you SMS from your brand name. Your PHP form handler saves the enquiry, cleans the mobile number and calls the API with a DLT template.

  • Keep only digits and drop a leading 91
  • Accept 10 digits starting with 6, 7, 8 or 9
  • Cut each variable to 40 characters
  • Log refusals instead of showing them to visitors

Full form guide with Contact Form 7

contact.phpPOST
<?php
// contact.php: thank the visitor by SMS after you save the enquiry
require __DIR__ . '/Fast2Sms.php';

$name   = trim($_POST['name'] ?? '');
$mobile = preg_replace('/\D/', '', $_POST['mobile'] ?? '');
if (strlen($mobile) === 12 && substr($mobile, 0, 2) === '91') {
    $mobile = substr($mobile, 2);            // drop the country code
}
if (preg_match('/^[6-9]\d{9}$/', $mobile) === 0) {
    http_response_code(422);
    exit('Please enter a valid 10-digit mobile number.');
}

// 1. save the enquiry in your database here

// 2. DLT template (Message ID 10002):
//    "Hi {#var#}, thanks for contacting Demo Traders.
//     We will call you within {#var#}. Demo Traders"
$sms = new Fast2Sms(getenv('FAST2SMS_API_KEY'));
$r = $sms->dlt('DEMOTR', '10002',
               [mb_substr($name, 0, 40), '2 hours'], [$mobile]);
if ($r['ok'] === false) {
    error_log('SMS refused: ' . json_encode($r['data']));
}

echo 'Thank you, we got your request.';
OTP SMS in PHP

Two ways to build OTP login in PHP

Let Fast2SMS make and check the code, or make it yourself and send it with your DLT OTP template.

Smart OTP: send, verify, resendPOST
<?php
// Smart OTP: Fast2SMS makes, sends and checks the code
session_start();
require __DIR__ . '/Fast2Sms.php';
$sms    = new Fast2Sms(getenv('FAST2SMS_API_KEY'));
$mobile = '9999999999';

// step 1: the user taps "Send OTP"
$send = $sms->post('/dev/otp/send', [
    'mobile'     => $mobile,
    'otp_id'     => 'YOUR_OTP_ID', // Smart OTP, Templates
    'otp_length' => 6,             // 4 to 10, default 6
    'otp_expiry' => 5,             // minutes, default 15
]);

// step 2: the user types the code
$check = $sms->post('/dev/otp/verify', [
    'mobile' => $mobile,
    'otp'    => $_POST['otp'] ?? '',
]);
if ($check['ok']) {
    $_SESSION['verified_mobile'] = $mobile; // log in
} else {
    // "OTP expired", "OTP not found or already verified" ...
    echo $check['data']['message'] ?? 'Could not verify';
}

// optional: send the same code again
$sms->post('/dev/otp/resend', ['mobile' => $mobile]);
Your own code with a DLT templatePOST
<?php
// Your own OTP with a DLT OTP template (Message ID 10003):
// "{#var#} is your Demo Traders login code. Valid for 5 minutes."
session_start();
require __DIR__ . '/Fast2Sms.php';

function send_login_otp(Fast2Sms $sms, string $mobile): bool
{
    $otp = (string) random_int(100000, 999999);
    $_SESSION['otp'] = [
        'mobile'  => $mobile,
        'hash'    => password_hash($otp, PASSWORD_DEFAULT),
        'expires' => time() + 300,
        'tries'   => 0,
    ];
    $r = $sms->dlt('DEMOTR', '10003', [$otp], [$mobile]);
    return $r['ok'];
}

function check_login_otp(string $mobile, string $typed): bool
{
    $o = $_SESSION['otp'] ?? null;
    if ($o === null || $o['mobile'] !== $mobile
        || time() > $o['expires'] || $o['tries'] >= 5) {
        return false;
    }
    $_SESSION['otp']['tries']++;
    if (password_verify($typed, $o['hash'])) {
        unset($_SESSION['otp']); // one use only
        return true;
    }
    return false;
}

When to use Smart OTP

You do not store any code. Verify needs no OTP ID: it always checks the latest unverified OTP for that mobile and answers "OTP verified successfully", "OTP expired" or "OTP not found or already verified". Send and resend are charged, verify is not.

  • Resend sends the same code again, within 10 minutes and up to 5 sends in total
  • A new send cancels every older OTP for that number
  • Templates can be SMS or WhatsApp, set in Smart OTP

When to make the code yourself

You already have an approved DLT OTP template and want full control. Generate the code with random_int, store only a hash with an expiry, limit the tries and delete it after one correct use. OTP templates are transactional, so they are not held at night.

  • Disable the Send button after one click until the API answers
  • Never send the OTP back to the browser
  • Same text to the same number within 10 seconds is refused (424)

More on OTPs: Smart OTP · PHP SMS and OTP guide

Bulk SMS API

Bulk sends, scheduling and Hindi SMS

One request can carry many numbers, comma separated, and every number gets the same text. For long lists, remove repeats and send batches with array_chunk, so a single timeout never touches the whole list. Add schedule_time to send at a set time, and sms_details to see the parts, rate and amount in each reply.

Hindi and other Indian languages work as plain UTF-8. The language is detected for you; there is no language parameter. If the template is in Hindi, it must be registered in Hindi with the same text.

  • English: 160 characters per part, 306 for 2, 459 for 3
  • Unicode: 70 per part, 133 for 2, 199 for 3
  • Invalid numbers are dropped and not charged
  • Different text per number: use /dev/custom
bulk-send.phpPOST
<?php
// one DLT template to a big list, in batches
require __DIR__ . '/Fast2Sms.php';
$sms     = new Fast2Sms(getenv('FAST2SMS_API_KEY'));
$numbers = array_values(array_unique($allNumbers)); // no repeats

foreach (array_chunk($numbers, 2000) as $i => $batch) {
    $r = $sms->dlt('DEMOTR', '10004', ['Rahul', '25 Nov'], $batch, [
        'schedule_time' => '25-11-2026-10-30', // IST, or a Unix time
        'sms_details'   => 1,
        'udf1'          => 'reminder-batch-' . $i,
    ]);
    if ($r['ok'] === false) {
        error_log("Batch $i refused: " . json_encode($r['data']));
    }
}

// Hindi works the same: send UTF-8 text in the values
$sms->dlt('DEMOTR', '10005', ['राहुल', '4821'], ['9999999999']);
Delivery reports

Delivery reports in PHP: pull or push

Pick one per message. Fetching a report with the API can stop the webhook from sending those same rows.

Pull: GET /dev/dlr/{request_id}GET
<?php
// check one send a few minutes later
$r = $sms->dlr('Sa1B2c3D4e5F6g7');
foreach ($r['data']['data'][0]['delivery_status'] ?? [] as $row) {
    // status: Delivered, Failed or Sent (report not in yet)
    echo $row['mobile'] . ' ' . $row['status'] . ' '
       . $row['status_description'] . PHP_EOL;
}

Looks back 7 days. For many messages use /dev/sms_logs (up to 3 days per call, 1 to 1,000 rows per page) or /dev/sms_summary (counts for up to 30 days).

Push: your webhook receiverPOST to you
<?php
// fast2sms-webhook.php: Fast2SMS posts each delivery status here.
// Optional: add your own header (X-Webhook-Token) in the
// webhook's Headers tab and check it first.
if (($_SERVER['HTTP_X_WEBHOOK_TOKEN'] ?? '') !== getenv('F2S_HOOK_TOKEN')) {
    http_response_code(401);
    exit;
}

$p = json_decode(file_get_contents('php://input'), true);
if (is_array($p)) {
    $requestId = $p['request_id'] ?? '';
    $mobile    = $p['mobile'] ?? '';
    $status    = $p['status'] ?? '';            // delivered or failed
    $reason    = $p['status_description'] ?? '';
    $orderId   = $p['udf1'] ?? '';              // what you sent
    // UPDATE messages SET status = ? WHERE request_id = ? AND mobile = ?
}

http_response_code(200); // answer fast, work later
echo 'OK';

Create it in the panel under Webhook, then SMS (or OTP), with method POST and JSON. Fast2SMS waits up to 10 seconds, retries up to 3 times 60 seconds apart on timeouts and 5xx, and keeps Webhook Logs for 7 days. Webhooks fire for API sends, not panel campaigns.

Errors

SMS API errors and how to fix them

A refused request returns "return": false with a status_code and a message. HTTP is 400 unless shown.

status_codeMessageFix
412 (HTTP 401)Invalid Authentication, Check Authorization KeyThe key is missing, wrong or was reset. Copy it again from API Key.
413 (HTTP 401)Invalid Authentication, Authorization Key DisabledTurn API Access on in API Key.
414 (HTTP 401)IP is blacklisted from Dev API sectionAPI Security is on. Add your server's public IP there.
405Numbers MissingAdd the numbers parameter.
406Invalid Sender IDUse your approved sender ID in the same case as DLT Manager.
411Invalid NumbersEvery number was invalid. Send 10-digit Indian mobiles starting with 6 to 9.
416You don't have sufficient wallet balanceRecharge. This can arrive with HTTP 200, so always read return.
422Invalid Variable Values or Some Values MissingSend one value per {#var#}, separated by |.
424Invalid Message ID (or Template, Entity ID)Send the short Message ID linked to that sender, not the 19-digit template ID.
424Same content to same number within 10 seconds not allowedStop double sends in your code; see the retry rules below.
425Invalid TemplateThe template is not approved yet. Check it in DLT Manager.
426Invalid link used in variablesLinks in variables must match what the template allows.
427Number blocked in Fast2SMS DND listThe person opted out at fast2sms.com/dnd. Remove the number.
428 (HTTP 401)Quick API Access is disabled.For route q, switch on Quick API Access in API Key.
999You need to complete one transaction of 100 INR or more before using API route.Quick SMS only. Recharge ₹100 or more once.

The full list is in the API documentation. To see exactly what your server sent, open the call in API Logs.

Go live safely

Security, retries and testing

Key on the server only

Read the key from an environment variable or a config file outside the public folder, and never commit it to a repository. Browser calls cause CORS errors and expose the key; if a key was ever public, reset it in API Key.

Lock it to your IP

Turn on API Security and add your server's public IP. Requests from any other address get 414. Shared hosting and serverless platforms need a fixed outgoing IP for this to work.

Retry with care

A timed out request may already have been accepted, and a blind retry sends and charges twice. Save your own message ID and the request_id, check API Logs before a retry, and retry only network failures that never reached the API.

Test with cURL first

Run the request in a terminal or Postman with your own number before writing PHP. If it works there, any problem in your app is in the code, not the account. The ₹50 signup credit covers these tests.

Use API Logs

Every call with a valid key appears in API Logs for 7 days with the endpoint, HTTP code, response, time and your server IP. Search by mobile, request ID or IP to answer "did it go?" in seconds.

Respect opt-outs

People can block business SMS from Fast2SMS at fast2sms.com/dnd; those numbers return 427 and are not charged. Keep your own opt-out list for promotional messages too.

SMS API pricing

No API fee. Pay per SMS.

Calls to the API are free. Each SMS costs your slab rate times the number of parts times the valid numbers, the same as sending from the panel. One rate covers promotional, transactional and OTP SMS. Quick SMS has its own rate, shown next to Quick API Access on the API Key page. There is no setup or monthly fee.

RechargePer SMS
₹100 to ₹3,999₹0.25
₹4,000 to ₹7,999₹0.21
₹8,000 to ₹13,999₹0.19
₹14,000 to ₹59,999₹0.17
₹60,000 to ₹1,29,999₹0.15
₹1,30,000 to ₹5,99,999₹0.13
₹6,00,000 or more₹0.11
Data security

Your data is encrypted and stays yours

Your customers' numbers and messages are business data. We treat them that way: encrypted on the wire and in the database, visible only to the people you allow, on infrastructure that is audited every year.

See our certificates
  • Encrypted in transitEvery panel page and API call runs over HTTPS (TLS 1.2+). Your API key is sent in a header, never in a page.
  • Encrypted at restSensitive fields such as API keys, templates and reports are encrypted in our database, with keys kept outside the application.
  • Access you controlPer-user API keys you can rotate any time, IP allow-listing, OTP on login, and agents who see only what you assign.
  • Audited and certifiedISO 27001 and SOC 2 Type 2 certified, VAPT tested by an external team, MSME registered.
ISO 27001 certified SOC 2 Type 2 VAPT certified MSME registered
FAQ

SMS API in PHP: questions answered

How do I send SMS from PHP?

Make a POST request with cURL to https://www.fast2sms.com/dev/bulkV2 with your API key in the authorization header and a JSON body with route, sender_id, message, variables_values and numbers. Read the JSON reply: "return": true with a request_id means the SMS was accepted. No library or Composer package is needed.

Is there a free SMS API for PHP?

The API itself is free: there is no API fee, setup fee or monthly fee. You pay only for the SMS you send, from ₹0.25 down to ₹0.11 per SMS depending on your recharge slab. New accounts get ₹50 free credit, so you can test the PHP code on real numbers before you recharge.

Do I need a PHP library or SDK?

No. The API is plain HTTPS with JSON, so the cURL functions that ship with PHP are enough. Laravel users can use the Http facade, CodeIgniter 4 users the CURLRequest service and WordPress sites wp_remote_post. This page has a small Fast2Sms class you can copy into any project.

Can I use GET instead of POST?

Yes. /dev/bulkV2 accepts the same parameters as a GET query string. Build the URL with http_build_query so spaces, the | sign and Hindi text are encoded correctly. POST with JSON is cleaner and keeps message values out of server logs.

What is the Message ID and where do I find it?

It is a short number Fast2SMS gives each approved template in DLT Manager, shown on the template card with a copy button. Send it as message on route dlt. It is not the 19-digit DLT Content Template ID; passing that long ID is the most common cause of error 424.

Can I send SMS without DLT registration from PHP?

Yes, with Quick SMS (route q). You send your own text and it goes from a random sender. Switch on Quick API Access in API Key and complete one recharge of ₹100 or more first. Requests with 10 or more numbers are held for a short manual check. For a branded sender and no review, register on DLT and use route dlt.

How do I send OTP SMS in PHP?

Two ways. With Smart OTP you call /dev/otp/send with the mobile and your OTP ID, then /dev/otp/verify with the code the user typed; Fast2SMS creates and checks the code. Or create the code yourself with random_int, save a hash with an expiry, and send it through your own DLT OTP template on route dlt.

How long is a Smart OTP valid?

You choose it with otp_expiry in minutes; the default is 15. otp_length sets 4 to 10 digits, default 6. Verify always checks the latest unverified OTP for that mobile, and sending a new OTP stops older ones from working. Resend sends the same code again within 10 minutes of the first send.

How many numbers can I send to in one PHP request?

Put them comma separated in numbers; every number gets the same text. No fixed maximum is published. For long lists, send batches of a few thousand with array_chunk so that one timeout does not affect the whole list. To send a different text to each number in one call, use /dev/custom.

How do I send Hindi SMS with PHP?

Send UTF-8 text. With JSON, json_encode with JSON_UNESCAPED_UNICODE keeps Hindi readable, and the default escaped form works too. The language is detected automatically. A Unicode SMS fits 70 characters in one part instead of 160, so a long Hindi message can cost 2 or 3 parts.

Can I schedule an SMS from PHP?

Yes. Add schedule_time as DD-MM-YYYY-HH-MM in IST, for example 25-11-2026-10-30, or as a Unix timestamp. It works on routes dlt, dlt_manual and q. The reply says "SMS scheduled successfully." A time in the past returns error 424.

How do I know if the SMS was delivered?

"SMS sent successfully." only means Fast2SMS accepted the message. For delivery, call GET /dev/dlr/{request_id} a few minutes later (it looks back 7 days), or create an SMS webhook in the panel and Fast2SMS posts delivered or failed to your PHP script. Use one method per message, because polling can stop the webhook for those rows.

Why does my PHP code say success when nothing was sent?

Probably it only checks the HTTP code. A low wallet balance can return HTTP 200 with "return": false and status_code 416. Always read the return field in the JSON and log status_code and message when it is false.

Why am I getting a CORS error?

You are calling the API from JavaScript in a browser. Move the call to PHP on your server and let your page call your own script. Any key placed in browser code can be copied by visitors and used to send SMS from your wallet.

How do I stop duplicate SMS when a request times out?

The SMS API has no idempotency key, so give each message your own unique ID, save it before you call the API, pass it in udf1 and save the request_id when it comes back. Before any retry, check your record and API Logs. Use a timeout of about 30 seconds so that most calls finish.

Can I lock the API key to my server IP?

Yes. Turn on API Security in the panel and add your server's public IP. Calls from any other address get status_code 414. Every call made with your key is also listed in API Logs for 7 days with the endpoint, response and IP.

Does the SMS API work on shared hosting?

Yes, if your host allows outgoing HTTPS requests and has the PHP cURL extension, which most do. If you use API Security, add the host's outgoing IP. Store the key in an environment variable or a config file outside the public folder.

How much does an SMS cost through the PHP API?

The same as the panel: ₹0.25 per SMS on recharges from ₹100 to ₹3,999, falling to ₹0.11 per SMS on recharges of ₹6,00,000 or more. One rate covers promotional, transactional and OTP SMS. A message is charged per part and per valid number; invalid numbers are not charged.

Is there a PHP sample for my own templates?

Yes. In DLT Manager, click Sample Code on a template card and choose PHP; the snippet already has your sender ID, Message ID and route. Account Setting also has an API Excel download with ready request URLs for your approved templates.

Can I get the wallet balance from PHP?

Yes. POST to https://www.fast2sms.com/dev/wallet with the authorization header. The reply has your balance and how many SMS it covers at your current rate, so your app can warn you before it runs out.

Send your first SMS from PHP today

Free API key, ₹50 test credit and no monthly fee. Copy the code above and you are live in minutes.