Send SMS from PHP with plain cURL, from the phone you already own
No Composer package, no Twilio number: PHP's own cURL extension, one function, and your phone does the sending. Then delivery status, safe retries, a CSV list and a webhook that checks its signature, all run on PHP 8.5.
Sparetext
8 min read · Nov 11, 2026
PHP runs a huge share of the small business web: the booking page, the WooCommerce shop, the admin panel someone wrote in 2014 that still works. So when that site needs to send a text, the usual answer is a Composer package, a paid number and a form for US carriers. If your texts go to people who already know you, there's a shorter way.
Sparetext turns the Android phone you already own into an SMS gateway with a plain HTTP API. Your PHP talks to our server, and the text goes out from your phone, on your number. Everything below uses the cURL extension that ships with almost every PHP install, and every sample ran on 11 November on PHP 8.5, against a test copy of Sparetext with a simulated phone on the other end.
What you need
- A Sparetext account. Free is 1 phone and 300 texts a month.
- An Android phone with the Sparetext app, paired in the dashboard. An iPhone works too, through Sparetext for Mac (the iPhone guide).
- An API key from the API keys page, in an environment variable called
SPARETEXT_API_KEY. On shared hosting, set it in the control panel or your framework's.env, never in a file people can download. - PHP 8 or later with the cURL extension. Check with
php -m | grep curl.
Send your first text
<?php
$api = 'https://sparetext.dev/api/v1';
$ch = curl_init("$api/messages");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'x-api-key: ' . getenv('SPARETEXT_API_KEY'),
'content-type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'to' => '+12025550151',
'text' => 'Your table for 2 is ready. See you soon!',
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
]);
$raw = curl_exec($ch);
if ($raw === false) {
exit('Network error: ' . curl_error($ch) . "\n");
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$body = json_decode($raw, true);
if ($status >= 400) {
exit("$status {$body['error']['code']}: {$body['error']['message']}\n");
}
print_r($body);Put your own number in to, with its country code, and run php send.php. Your phone sends the text a moment later, and the answer has a batchId and the message with its id and status, which starts at queued.
Three things in there catch people. curl_exec returns false only when the network fails; a 401 or a 500 comes back as a normal string, so you check the status code yourself. Without CURLOPT_RETURNTRANSFER it prints the answer instead of returning it. And without CURLOPT_TIMEOUT a stuck connection can hold your page until PHP's own time limit kills it.
With a bad key, our test printed 401 unauthorized: That key or token is not valid. It may have been revoked. Every error has that shape: a code to test in code, a message for people.
One function for every call
Copying that block around gets old fast. This function does the same thing for any call, throws with the API's own error, and also keeps the Retry-After header, which you'll want in a minute:
<?php
// One function for every call: it returns the decoded answer, or throws with the API's own error.
function sparetext(string $method, string $path, ?array $payload = null, array $headers = []): array
{
$ch = curl_init('https://sparetext.dev/api/v1' . $path);
$retryAfter = null;
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => array_merge([
'x-api-key: ' . getenv('SPARETEXT_API_KEY'),
'content-type: application/json',
], $headers),
CURLOPT_POSTFIELDS => $payload === null ? null : json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, 'retry-after:') === 0) {
$retryAfter = (int) trim(substr($line, 12));
}
return strlen($line);
},
]);
$raw = curl_exec($ch);
if ($raw === false) {
throw new RuntimeException('Network error: ' . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$body = $raw === '' ? [] : json_decode($raw, true);
if ($status >= 400) {
throw new SparetextError($status, $body['error']['code'], $body['error']['message'], $retryAfter);
}
return $body;
}
class SparetextError extends RuntimeException
{
public function __construct(public int $status, public string $errorCode, string $message, public ?int $retryAfter)
{
parent::__construct("$status $errorCode: $message");
}
}Check that it arrived
queued means the text is waiting for your phone. It then moves to dispatched (the phone has it), sent, and delivered if your carrier sends delivery reports. A text that goes wrong ends at failed, with the reason in error.
<?php
require __DIR__ . '/sparetext.php';
$sent = sparetext('POST', '/messages', [
'to' => '+12025550152',
'text' => 'Your order #1042 is out for delivery.',
]);
$id = $sent['messages'][0]['id'];
echo "$id {$sent['messages'][0]['status']}\n";
$deadline = time() + 120;
do {
sleep(3);
$message = sparetext('GET', "/messages/$id")['message'];
} while (!in_array($message['status'], ['delivered', 'failed', 'canceled'], true) && time() < $deadline);
echo $message['status'], ' ', $message['error'] ?? '', "\n";Against the simulated phone it printed queued, then delivered on the first check. A real phone on a real network takes longer, and some carriers never send a delivery report at all, so a text can rest at sent. That's why the loop gives up after two minutes. Don't run a loop like this inside a web request, by the way: send the text, show the page, and let a webhook (below) tell you how it went.
Retry without texting someone twice
Here's the thing about retries and SMS. If your request times out, you don't know whether the text was queued. Send again blindly and your customer gets the same text twice, which for a payment reminder looks broken.
The fix is an Idempotency-Key header: any unique string you make up. Send the same key again and Sparetext hands back the first answer instead of queuing a second text. Keys are kept for 24 hours. This function makes one key per text, keeps it across tries, and waits out a 429 when you send too fast:
<?php
require __DIR__ . '/sparetext.php';
function sendText(array $payload, int $tries = 4): array
{
$key = bin2hex(random_bytes(16)); // the same key on every try, so a retry can't send twice
for ($attempt = 1; ; $attempt++) {
try {
return sparetext('POST', '/messages', $payload, ["idempotency-key: $key"]);
} catch (SparetextError $e) {
if ($e->status !== 429 || $e->retryAfter === null || $attempt >= $tries) {
throw $e; // a bad number or a daily key limit won't fix itself
}
sleep($e->retryAfter);
} catch (RuntimeException $e) {
if ($attempt >= $tries) {
throw $e; // timeout or network error: try again with the same key
}
sleep($attempt);
}
}
}We checked both halves. The same key sent twice came back with the same message id, and only one text was queued. The same key with different words was refused with 422 idempotency_mismatch, so a bug can't quietly reuse a key for another text.
An account can make 15 send requests every 5 seconds; past that the API answers 429 rate_limited with Retry-After in seconds. We sent 30 texts in a row through sendText: it was told to wait once, for 5 seconds, and all 30 went through in under 6. One 429 has no Retry-After on purpose: key_daily_limit, when a key has used up the texts you allowed it for the day, and the function throws on that one.
Text a list from a CSV
Most PHP shops can export a CSV: tomorrow's bookings, orders waiting for pickup. One request carries up to 100 people, each with their own words:
<?php
require __DIR__ . '/sparetext.php';
$file = fopen('bookings.csv', 'r');
$columns = fgetcsv($file, null, ',', '"', ''); // name,phone,time
$messages = [];
while (($row = fgetcsv($file, null, ',', '"', '')) !== false) {
$b = array_combine($columns, $row);
$messages[] = [
'to' => $b['phone'],
'text' => "Hi {$b['name']}, see you tomorrow at {$b['time']}. Reply YES to confirm.",
];
}
foreach (array_chunk($messages, 100) as $chunk) {
$batch = sparetext('POST', '/messages', ['messages' => $chunk]);
echo $batch['batchId'], ': ', count($batch['messages']), " queued, last one out about {$batch['estimatedCompletionAt']}\n";
}Those extra fgetcsv arguments aren't decoration. Since PHP 8.4, leaving out the escape argument prints a deprecation warning, because its default is going to change. Passing '' turns the old backslash escaping off, which is what a normal spreadsheet export wants. Our test file had a name with a comma in it, in quotes, and it came through in one piece.
Your phone sends at about 30 texts a minute, under Android's own limit, so a long list takes a while to leave even though the request returns at once. estimatedCompletionAt says when the last one should go.
Get replies with a webhook
For a site, a webhook beats polling: Sparetext posts each text your phone receives to a URL you choose. Anyone who finds that URL can post to it too, so the script checks the X-Sparetext-Signature header first. It looks like t=1793438045,v1=9c2f…: a timestamp, then an HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the webhook's secret.
<?php
// Sparetext calls this URL for every text your phone receives.
function fromSparetext(string $raw, string $header, string $secret): bool
{
if (!preg_match('/(?:^|,)t=(\d+)/', $header, $t) || abs(time() - (int) $t[1]) > 300) {
return false; // missing, or more than five minutes off: maybe a replayed request
}
$want = hash_hmac('sha256', "$t[1].$raw", $secret);
preg_match_all('/v1=([0-9a-f]{64})/', $header, $v1);
foreach ($v1[1] as $got) {
if (hash_equals($want, $got)) {
return true;
}
}
return false;
}
$raw = file_get_contents('php://input'); // the bytes exactly as they arrived
$header = $_SERVER['HTTP_X_SPARETEXT_SIGNATURE'] ?? '';
if (!fromSparetext($raw, $header, getenv('SPARETEXT_WEBHOOK_SECRET'))) {
http_response_code(401);
exit;
}
$event = json_decode($raw, true);
if ($event['type'] === 'message.received') {
$text = $event['data']['message'];
error_log("{$text['contact']} said: {$text['text']}");
}
http_response_code(200);Read the body from php://input, not $_POST: the signature covers the exact bytes, and $_POST is empty for JSON anyway. hash_equals compares in constant time, so nobody can guess the signature one character at a time. The loop accepts either v1= value because for a day after you rotate the secret there are two.
We ran it under php -S, added it on the Webhooks page with Text received ticked, and texted the simulated phone. The real signed delivery got a 200 and the log said +12025550157 said: YES. A plain POST without a signature got a 401. The webhook guide has the full event list and how retries work.
What this can't do
A phone is the right tool for texts to people who know you: booking reminders, order updates, alerts to your team, replies to customers. For login codes there's a ready-made verify endpoint, so you don't store codes yourself.
It's the wrong tool for marketing to a list that didn't ask. Carriers filter business texts sent by software even from a personal number, and the 10DLC post explains why. An iPhone can't send silently in the background the way Android can, and only Android phones get carrier delivery reports. On plans, Free covers 300 texts a month and Pro 10,000 on up to 5 phones (pricing).
The same steps exist for Node.js, Python, Go, Ruby and Java. For a quick alert from a server, curl in a bash script is enough.
Try it with your own number
Make a key on the API keys page, pair your phone, and run php send.php with your own number in to. When your pocket buzzes, drop sparetext.php and sendText into your site and send the first real reminder.
phpsend smssms apicurlwebhookstutorial
Try it with the phone you have
Free for 1 phone and 300 texts a month. Pair it in about two minutes.
Responses
Sign in or create an account to respond.