Key facts

  • Install and verify PDO_SQLITE, connect PHP to an SQLite database, use prepared statements and transactions, and fix driver, permission, or locking errors.
  • Confirm that PDO::getAvailableDrivers() contains sqlite before changing configuration.
  • On Ubuntu or Debian, install the distribution package with sudo apt install php-sqlite3 if the driver is missing.

PDO_SQLITE lets PHP applications use SQLite through the same PDO interface used for other databases. In a standard PHP build, PDO and the SQLite PDO driver are normally enabled by default. On a minimal server image or a distribution that splits extensions into packages, you may still need to install or enable the driver.

Start with evidence: check the PHP runtime that actually handles your application before editing php.ini. Command-line PHP and PHP-FPM or Apache can load different versions and different configuration files.

Quick answer: enable PDO_SQLITE

  1. Confirm that PDO::getAvailableDrivers() contains sqlite before changing configuration.
  2. On Ubuntu or Debian, install the distribution package with sudo apt install php-sqlite3 if the driver is missing.
  3. Restart the PHP service that serves the website, then verify the driver through that same web runtime.
  4. Connect with an absolute DSN such as sqlite:/var/lib/myapp/app.sqlite and give the PHP service account write access to the database directory when writes are required.
php -r 'var_export(PDO::getAvailableDrivers());'
php --ri pdo_sqlite
php --ini

If the first command lists sqlite, the CLI driver is available. That result does not prove that a website using PHP-FPM or an Apache module loads the same extension, so use the runtime checks below before closing the issue.

What PDO_SQLITE does

PDO is PHP's database access interface. PDO_SQLITE is its SQLite driver. SQLite stores a database in a local file instead of connecting to a separate database server. This makes it useful for command-line tools, small web applications, local caches, test suites, prototypes, and applications with modest write concurrency.

PDO_SQLITE and the separate SQLite3 PHP extension can both access SQLite, but their APIs are different. Use PDO_SQLITE when your application is written around PDO, needs prepared statements through PDO, or should keep a similar database abstraction across environments. Installing php-sqlite3 on Debian-family systems commonly provides both SQLite extensions for the selected PHP version.

Check whether the SQLite PDO driver is available

Use more than one check. The list of PDO drivers answers the practical question, while the module information shows how the driver was loaded:

php -r 'print_r(PDO::getAvailableDrivers());'
php -m | grep -iE 'pdo|sqlite'
php --ri pdo_sqlite

A working result should include sqlite in the PDO driver list and show a PDO SQLite section. If PHP reports Class "PDO" not found, the base PDO extension is unavailable. If PDO exists but sqlite is absent, install or enable PDO_SQLITE.

Avoid publishing a phpinfo() page on a public website. It can expose file paths, environment data, loaded extensions, and server configuration. If you need a web-runtime check, use a temporary restricted script and delete it after diagnosis:

<?php
header('Content-Type: text/plain; charset=utf-8');
var_export([
    'php' => PHP_VERSION,
    'sapi' => PHP_SAPI,
    'ini' => php_ini_loaded_file(),
    'drivers' => PDO::getAvailableDrivers(),
]);

Install PDO_SQLITE on Ubuntu or Debian

Ubuntu publishes php-sqlite3 as the default SQLite module package. It depends on the versioned package selected by the distribution, so the exact PHP version can differ between Ubuntu releases. Start with the unversioned package unless your server deliberately runs a specific third-party PHP stack:

sudo apt update
sudo apt install php-sqlite3

php -r 'var_export(PDO::getAvailableDrivers());'

If the site still reports a missing driver, identify the active PHP version and service before installing a version-specific package:

php -v
apt-cache policy php-sqlite3
systemctl list-units --type=service 'php*-fpm.service'

For example, a server intentionally running PHP 8.3 may use php8.3-sqlite3. Do not guess the version from an old tutorial. Match the package to the runtime configured for the site.

Restart the PHP runtime after installation

Restart the component that keeps PHP processes in memory. Restarting Nginx alone normally does not reload PHP-FPM extensions.

# Example for a server using PHP 8.3 FPM
sudo systemctl restart php8.3-fpm

# Example for Apache with mod_php
sudo systemctl restart apache2

Replace 8.3 with the version returned by your service inventory. Then run the temporary web-runtime check again. A package installation plus an HTTP 200 response is not enough; the web SAPI must list sqlite in PDO::getAvailableDrivers().

Enable PDO_SQLITE on Windows and custom PHP builds

Official PHP documentation states that PDO and PDO_SQLITE are enabled by default in standard builds. If a Windows distribution ships the driver as a shared extension, find the active php.ini, verify extension_dir, and enable the extension line provided by that distribution, commonly:

extension=pdo_sqlite

On Windows, the PHP manual also requires libsqlite3.dll to be available on the system PATH. Keep DLLs from the same PHP distribution together instead of downloading individual files from an unrelated site. Restart the web server or PHP process after changing configuration.

For a custom source build, compile PHP with PDO SQLite support and the required SQLite library. Current PHP documentation notes that PHP 8.5 requires SQLite 3.7.17 or newer. Use the build documentation for the exact PHP branch instead of copying obsolete configure flags.

Make CLI and web PHP use the same intended configuration

The most common diagnostic trap is checking one SAPI and serving the application with another. These commands help identify the difference:

# CLI binary and configuration
command -v php
php -v
php --ini

# FPM services installed on the host
systemctl list-unit-files 'php*-fpm.service'

# Nginx upstream configuration, if used
grep -R "fastcgi_pass" /etc/nginx/sites-enabled/

If CLI uses PHP 8.4 but Nginx sends requests to PHP 8.3 FPM, installing the 8.4 package will not fix the website. Align the package, pool, socket, and configuration with the runtime the virtual host actually uses.

Connect PHP to an SQLite database

The PDO SQLite DSN begins with sqlite:. Use an absolute file path in production so the database location does not depend on the process working directory:

<?php
$databasePath = __DIR__ . '/data/app.sqlite';

$pdo = new PDO('sqlite:' . $databasePath, null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$pdo->exec('PRAGMA foreign_keys = ON');
$pdo->exec('PRAGMA busy_timeout = 5000');

sqlite::memory: creates an in-memory database for the lifetime of the connection. A bare sqlite: DSN creates a temporary on-disk database. Most persistent applications should use an explicit absolute path.

Create a table and run a query

The following complete example creates a small notes table, inserts one row safely, and reads the result:

<?php
$databasePath = __DIR__ . '/data/app.sqlite';
$pdo = new PDO('sqlite:' . $databasePath, null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('PRAGMA foreign_keys = ON');

$pdo->exec(
    'CREATE TABLE IF NOT EXISTS notes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        body TEXT NOT NULL,
        created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
    )'
);

$insert = $pdo->prepare(
    'INSERT INTO notes (title, body) VALUES (:title, :body)'
);
$insert->execute([
    'title' => 'First note',
    'body' => 'PDO_SQLITE is working.',
]);

$notes = $pdo->query(
    'SELECT id, title, body, created_at FROM notes ORDER BY id DESC'
)->fetchAll();

var_export($notes);

This example uses exceptions for errors and associative arrays for fetched rows. In an application, handle exceptions at a boundary that can log technical details privately while returning a safe response to the user.

Use prepared statements for values

Do not concatenate request data into SQL. Prepare the statement once and pass values separately:

$statement = $pdo->prepare(
    'SELECT id, title, body FROM notes WHERE title = :title'
);
$statement->execute(['title' => $requestedTitle]);
$note = $statement->fetch();

Prepared statements handle data values, not SQL identifiers. If a user can choose a sort column or table name, map the input to a small allowlist instead of binding it as a parameter or inserting it directly.

Use transactions for grouped writes

A transaction keeps a related set of writes together. Commit only after every statement succeeds, and roll back when an exception interrupts the operation:

try {
    $pdo->beginTransaction();

    $statement = $pdo->prepare(
        'INSERT INTO notes (title, body) VALUES (:title, :body)'
    );
    $statement->execute(['title' => 'A', 'body' => 'First']);
    $statement->execute(['title' => 'B', 'body' => 'Second']);

    $pdo->commit();
} catch (Throwable $error) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    throw $error;
}

Transactions also reduce lock churn when many inserts belong to one operation. Keep them short. Network requests, file uploads, and slow external API calls should normally happen outside the database transaction.

Enable foreign key enforcement explicitly

SQLite foreign-key enforcement has historically defaulted to off, and the default can be changed at compile time. Set it explicitly for every new connection instead of assuming:

$pdo->exec('PRAGMA foreign_keys = ON');

$enabled = $pdo->query('PRAGMA foreign_keys')->fetchColumn();
if ((int) $enabled !== 1) {
    throw new RuntimeException('SQLite foreign keys are not enabled.');
}

Run the setting before beginning a transaction. Changing PRAGMA foreign_keys inside an active transaction has no effect.

Set database path and permissions correctly

An SQLite connection may create the database file when it does not exist, but the parent directory must be writable by the PHP service account. Updates can also require temporary journal or WAL files beside the database. Give the application the narrow access it needs:

  • Create a dedicated application data directory outside the public document root when possible.
  • Assign ownership or group access to the actual PHP-FPM or Apache service account.
  • Keep the database, WAL, journal, and backups out of downloadable web paths.
  • Do not use chmod 777 as a permanent fix.
  • Back up the database with an SQLite-aware method while the application can write to it.

If reads work but writes fail, inspect both the file and its parent directory. Also check mandatory access controls such as AppArmor or SELinux when Unix permissions appear correct.

Fix common PDO_SQLITE errors

Error or symptomLikely causeSafe next check
could not find driverPDO exists, but the web runtime did not load PDO_SQLITECompare PDO::getAvailableDrivers(), PHP version, SAPI, and loaded php.ini in CLI and web contexts
unable to open database fileWrong path, missing directory, or denied directory accessResolve the absolute path and test permissions as the PHP service account
attempt to write a readonly databaseThe database or its directory is not writable, or the filesystem is read-onlyCheck ownership, parent directory permissions, mount state, and security policy
database is lockedAnother write transaction is active or a transaction stays open too longShorten transactions, add a bounded busy timeout, and inspect concurrent writers
CLI works, browser failsDifferent PHP version, SAPI, configuration, or FPM poolRun the restricted web-runtime check and follow the web server's upstream socket
no such tableThe application opened another database file or migrations did not runLog the resolved absolute path and query sqlite_master
Foreign keys are ignoredPRAGMA foreign_keys was not enabled on this connectionEnable and verify it immediately after connecting
database disk image is malformedPossible corruption or a broken copyStop writes, preserve the files, work from a copy, and follow SQLite recovery guidance

Fix “database is locked” without hiding the cause

SQLite permits multiple readers but only one writer at a time. A short busy timeout lets a connection wait briefly instead of failing immediately:

$pdo->exec('PRAGMA busy_timeout = 5000');

This is a five-second ceiling, not a concurrency strategy. Find long transactions, uncommitted error paths, background jobs that write in batches, or requests that hold a transaction while doing unrelated work. Retry only bounded, idempotent operations. If sustained concurrent writes are a core workload, a client-server database may be a better fit.

Decide whether to enable WAL mode

Write-ahead logging can improve read and write overlap because readers can continue while a writer appends to the WAL. It does not allow multiple simultaneous writers, and all processes must access the database on the same host. SQLite documentation states that WAL does not work over a network filesystem.

$journalMode = $pdo->query('PRAGMA journal_mode = WAL')->fetchColumn();
if (strtolower((string) $journalMode) !== 'wal') {
    throw new RuntimeException('SQLite WAL mode was not enabled.');
}

Use a maintained SQLite package before enabling WAL in a multi-process application. SQLite documented a rare WAL-reset corruption bug fixed in 3.51.3 and in backports 3.44.6 and 3.50.7. Check the library version used by PHP, test backup and restore, and monitor checkpoint behavior.

Frequently asked questions

Is PDO_SQLITE enabled by default?

Yes, in standard PHP builds PDO and PDO_SQLITE are enabled by default. Minimal images, distribution packaging, custom builds, and disabled shared extensions can still leave the driver unavailable at runtime.

How do I install PDO_SQLITE on Ubuntu?

Run sudo apt update and sudo apt install php-sqlite3, then restart the active PHP-FPM service or Apache. Verify through the same SAPI that serves the site.

What is the PDO SQLite connection string?

Use sqlite:/absolute/path/to/database.sqlite for a persistent file or sqlite::memory: for an in-memory database.

Will PDO create the SQLite file?

A writable connection can create a missing database file. The parent directory must exist and be writable by the PHP process. Use an absolute path so you know where the file will be created.

Should I use PDO_SQLITE or the SQLite3 extension?

Use PDO_SQLITE when the application already uses PDO or benefits from a consistent PDO interface. Use SQLite3 when the application specifically depends on that extension's API. Both access the same SQLite database format.

Can PDO_SQLITE be used in production?

Yes, for workloads that fit SQLite's local-file model and single-writer design. Store the file securely, keep transactions short, use tested backups, and choose a client-server database when write concurrency or multi-host access becomes central.

Sources and scope

This guide was reviewed on October 14, 2026 against the official PHP PDO_SQLITE documentation, PDO installation guide, PDO SQLite DSN reference, PDO driver check, Ubuntu package index, and SQLite's official PRAGMA, transaction, and WAL documentation. Package names, service versions, and filesystem policy remain specific to your server.