Offline Writes with Turso Connection
Offline writes allow your PHP application to continue functioning even when the database is temporarily unreachable. Instead of failing immediately, writes are stored locally in a replica file and later synchronized to the primary Turso database once connectivity is restored.
This makes your app resilient to network issues — perfect for mobile, edge, or distributed systems.
Example
<?php
$authToken = getenv("TURSO_AUTH_TOKEN");
$dbUrl = getenv("TURSO_DB_URL");
$config = [
"url" => "file:database.db", // Local replica storage
"authToken" => $authToken, // Auth token for Turso
"syncUrl" => $dbUrl // Remote Turso DB endpoint
];
// Open connection in offline mode
//
// PHP note: extension functions with unknown default values can't have
// named-argument slots skipped, so every parameter before the last one you
// pass must be passed explicitly or the constructor rejects the call.
$db = new LibSQL(
config: $config,
sqld_offline_mode: false, // Turso Cloud flavor (see API notes below)
flags: LibSQL::OPEN_READWRITE | LibSQL::OPEN_CREATE,
encryption_key: "",
offline_writes: true
);
function saveNote(string $content)
{
global $db;
// Ensure table exists
$sql = "CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY,
content TEXT,
created_at TEXT
)";
$db->execute($sql);
// Insert new note
$sql = "INSERT INTO notes (content, created_at) VALUES (?, datetime('now'))";
$parameters = [$content];
$db->execute($sql, $parameters);
// Attempt sync to remote Turso
try {
$db->sync();
echo "Note synced to cloud" . PHP_EOL;
} catch (Exception $e) {
// If offline, store locally until network is restored
echo $e->getMessage() . PHP_EOL;
echo "Note saved locally, will sync later" . PHP_EOL;
}
}
function readNotes()
{
global $db;
$sql = "SELECT * FROM notes";
$result = $db->query($sql);
$rows = $result->fetchArray(LibSQL::LIBSQL_ASSOC);
foreach ($rows as $row) {
echo $row["content"] . PHP_EOL;
}
}
// Demo: Save a random note and read notes
$random = rand(1, 100);
saveNote("Note $random");
readNotes();
How It Works
-
Configuration
url: A local file (file:database.db) acts as the replica storage.authToken: Your Turso authentication token.syncUrl: The remote Turso database endpoint.offline_writes: true: Enables local persistence when offline.
-
Saving Notes (
saveNote)- Ensures a
notestable exists. - Inserts a new note with a timestamp.
- Calls
$db->sync()to push changes to the cloud. - If syncing fails (e.g., offline), the note stays local and syncs later.
- Ensures a
-
Reading Notes (
readNotes)- Fetches all notes from the local replica.
- Even if offline, you can still read previously stored notes.
-
Resiliency
- Application continues to accept writes.
- Data is durable locally.
- Sync automatically restores consistency with the remote when available.
Usage
- ✅ Mobile apps or IoT devices where connectivity is unreliable
- ✅ Edge deployments with temporary offline mode
- ✅ Applications needing guaranteed durability even without network access
- ⚠️ Always handle sync errors gracefully (see
try/catchin example)
Best Practices
- Run periodic
$db->sync()calls in a background job or cron. - Monitor sync errors and retry strategies.
- Keep local replica files (
database.db) in a persistent storage volume. - For multi-device sync, always rely on the remote Turso DB as the source of truth.
Offline-Write Mode API Notes
The Turso Cloud flavor uses libSQL’s built-in synced database: writes are persisted locally and pushed to the remote in the background.
- Creating the connection needs the
syncUrlto be reachable once at construction time; after that, writes are buffered locally when offline. prepare()andtransaction()work in this flavor — it is the journaledsqld_offline_mode: trueflavor where they throw (see the sqld offline writes docs).getPendingOperationsCount()/isOnline()only apply to the sqld flavor; here the local sync status is managed by libSQL itself.
Next Steps
- 👉 Offline Writes: Flavor Comparison — side-by-side matrix of both offline-write flavors
- 👉 Offline Writes (libSQL Server/sqld) Connection — the journaled offline-write flavor
- 👉 Core API — learn all available methods
- 👉 Transactions API — ensure atomic writes
- 👉 Sync API — understand synchronization in detail