Connect PHP to SQL Server on Ubuntu 18.04

An existing Ubuntu 18.04 x64 host running PHP 8.2 can connect to SQL Server with Microsoft Open Database Connectivity (ODBC) Driver 17 and the sqlsrv 5.11.1 PHP extension. This procedure is for maintaining a legacy server. For a new installation or migration, select a currently supported OS and PHP combination from Microsoft’s matrix.

Check Ubuntu, PHP, and driver versions

Ubuntu 18.04 standard security maintenance ended in 2023. Check Expanded Security Maintenance (ESM) through Ubuntu Pro and separately verify patch coverage for the PHP packages from your provider. Upstream PHP 8.2 security support runs through December 31, 2026. Microsoft lists Ubuntu 18.04 and PHP 8.2 for the 5.11 driver line. Ubuntu 18.04 was dropped in 5.12. Canonical · Ubuntu Expanded Security Maintenance PHP · Supported Versions Microsoft Learn · PHP Driver Support Matrix Microsoft Learn · PHP Driver Release Notes

Compare the PHP executable and configuration with the PHP build tools and PECL (PHP Extension Community Library) listed below. If the tools are absent, obtain matching development packages from the same trusted source and recheck before building. Stop if the system selects Ubuntu’s original PHP 7.2 or another PHP build toolchain. Check the web runtime version separately from the command line. Check the web version with phpversion() on a restricted test path.

cat /etc/os-release
uname -m
php -v
php --ini
phpize --version
php-config --version
pecl version

Install ODBC Driver 17 and SQLSRV 5.11.1

Have the SQL Server hostname and TCP port, database, a login with access, and a trusted certificate chain ready. Skip repository registration if the official Ubuntu 18.04 repository is already configured. Review and accept the license terms before using ACCEPT_EULA=Y. Microsoft Learn · Install Microsoft ODBC Driver 17

curl -fsSLo packages-microsoft-prod.deb https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
apt-cache policy msodbcsql17 php8.2-dev
sudo ACCEPT_EULA=Y apt-get install msodbcsql17 unixodbc-dev
odbcinst -q -d
dpkg-query -W msodbcsql17

Check that the package is version 17.4.2 or later in the 17 series and that odbcinst lists ODBC Driver 17 for SQL Server. If trusted repositories cannot supply matching PHP 8.2 development packages, migrate to a supported setup. Install pdo_sqlsrv only if your application uses PHP Data Objects (PDO). The connection check below uses sqlsrv. PECL · sqlsrv 5.11.1

sudo apt-get install build-essential php-pear php8.2-dev php8.2-xml
sudo phpize --version
sudo php-config --version
sudo pecl version
sudo pecl install sqlsrv-5.11.1
sudo pecl install pdo_sqlsrv-5.11.1

Enable the extensions for CLI and web PHP

On Debian-style PHP packages, check or create /etc/php/8.2/mods-available/sqlsrv.ini and, for PDO, pdo_sqlsrv.ini. Reuse an existing loader entry if present. The following blocks are the contents of the two files. PDO must load before pdo_sqlsrv. Microsoft Learn · Loading the PHP SQL Driver

; priority=20
extension=sqlsrv.so
; priority=30
extension=pdo_sqlsrv.so

Verify the extensions in CLI PHP first. Then use only the Apache module or PHP FastCGI Process Manager (PHP-FPM) commands for the server interface (SAPI) that actually processes PHP requests. Omit pdo_sqlsrv from every phpenmod command if you skipped that extension.

sudo phpenmod -v 8.2 -s cli sqlsrv pdo_sqlsrv
php8.2 --ri sqlsrv
php8.2 --ri pdo_sqlsrv

Apache module

sudo phpenmod -v 8.2 -s apache2 sqlsrv pdo_sqlsrv
sudo apache2ctl configtest
sudo systemctl restart apache2

PHP-FPM

sudo phpenmod -v 8.2 -s fpm sqlsrv pdo_sqlsrv
sudo systemctl restart php8.2-fpm

Run an encrypted connection check

Make a public directory in your test folder and keep sqlserver-config.php outside it. Replace the example hostname with the name covered by the server certificate and fill in the actual port, account, and database. Keep the configuration out of public paths and version control.

<?php
return [
    'server' => 'tcp:db.example.test,1433',
    'database' => 'your_database',
    'username' => 'your_application_user',
    'password' => 'REPLACE_WITH_YOUR_PRIVATE_PASSWORD',
];

Save the connection check in UTF-8 as public/sqlserver-check.php. Run it through web PHP on a restricted test route, or run php8.2 public/sqlserver-check.php from the test folder. Check CLI and web PHP separately.

<?php
header('Content-Type: text/plain; charset=UTF-8');
if (!function_exists('sqlsrv_connect')) {
    http_response_code(500);
    echo 'The sqlsrv extension is not loaded for this PHP runtime.', PHP_EOL;
    exit(1);
}
function failSql($stage, $errors): void {
    $codes = [];
    foreach ($errors ?? [] as $error) {
        $codes[] = ['SQLSTATE' => $error['SQLSTATE'], 'code' => $error['code']];
    }
    error_log($stage . ': ' . json_encode($codes));
    http_response_code(500);
    echo 'SQL Server check failed. Review the server log.', PHP_EOL;
    exit(1);
}
$c = require dirname(__DIR__) . '/sqlserver-config.php';
$conn = sqlsrv_connect($c['server'], [
    'Database' => $c['database'], 'UID' => $c['username'], 'PWD' => $c['password'],
    'Driver' => 'ODBC Driver 17 for SQL Server',
    'CharacterSet' => 'UTF-8', 'LoginTimeout' => 5,
    'Encrypt' => true, 'TrustServerCertificate' => false,
]);
if ($conn === false) {
    failSql('connect', sqlsrv_errors());
}
$stmt = sqlsrv_query($conn, "SELECT 1 AS connected, N'Connection verified' AS message");
if ($stmt === false) {
    $errors = sqlsrv_errors();
    sqlsrv_close($conn);
    failSql('query', $errors);
}
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$errors = sqlsrv_errors();
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
if (!is_array($row)) {
    failSql('fetch', $errors);
}
echo $row['message'], ': ', $row['connected'], PHP_EOL;

Success prints Connection verified: 1. The query reads constants and leaves tables untouched. Errors log the stage, SQLSTATE, and driver code, while the response shows a generic message. Encryption and certificate verification stay enabled. On Linux, connection pooling is controlled by odbcinst.ini and the PHP ConnectionPooling option cannot disable it. Microsoft Learn · Connection Options Microsoft Learn · Connection Pooling

Find the failing layer and restore settings

Symptom First check
Function missing Web SAPI version and extension loading
ODBC driver error Registered driver name and package version
Connection timeout DNS, TCP port, and SQL Server listener
Login failure Authentication mode and account access to the database
Certificate error Hostname, validity, and trust chain
CLI works but web PHP fails Loaded ini files and service user

Use the table to identify the failing layer. Remove the diagnostic script after testing. To roll back, restore the changed extension or service settings from their backups and restart the affected service. Leave shared PHP versions and modules in place.