Connecting your PHP or Laravel application to Microsoft SQL Server on a Debian-based Linux server (like Debian 12, Ubuntu, etc.) requires ODBC and SQLSRV drivers.
By default, these are not included in Debian repositories, but Microsoft provides official packages to make it possible.
Hereβs a complete step-by-step guide on how to install and configure the SQLSRV extension on Debian, especially useful for Laravel apps.
Run the following to install the tools needed for building PHP extensions:
sudo apt update
sudo apt install -y gnupg2 lsb-release apt-transport-https software-properties-common
This is necessary to install the official ODBC driver:
# Import Microsoft's GPG key
curl -sSL https://packages.microsoft.com/keys/microsoft.asc | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc
# Add the repo to APT sources
curl -sSL https://packages.microsoft.com/config/debian/12/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list
# Update package list
sudo apt update
sudo ACCEPT_EULA=Y apt install -y msodbcsql17 unixodbc-dev
β If you prefer ODBC Driver 18:
sudo ACCEPT_EULA=Y apt install -y msodbcsql18
These are required to compile and install the PHP extensions via PECL:
sudo apt install -y php8.3-dev php-pear g++
Replace php8.3-dev with your PHP version (php8.2-dev, etc.) if you’re not on 8.3.
Install the drivers via PECL:
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv
Create INI files to load the extensions:
echo "extension=sqlsrv.so" | sudo tee /etc/php/8.3/mods-available/sqlsrv.ini
echo "extension=pdo_sqlsrv.so" | sudo tee /etc/php/8.3/mods-available/pdo_sqlsrv.ini
# Enable them
sudo phpenmod sqlsrv pdo_sqlsrv
Again, adjust the PHP version if you’re not on 8.3.
If you’re using PHP-FPM:
sudo systemctl restart php8.3-fpm
If you’re using Apache:
sudo systemctl restart apache2
Run:
php -m | grep sqlsrv
You should see:
pdo_sqlsrv
sqlsrv
You can also check with:
php -i | grep -i sqlsrv
<?php
$server = "your-sql-server-ip";
$connectionInfo = [
"Database" => "your_database",
"UID" => "your_username",
"PWD" => "your_password",
"TrustServerCertificate" => "yes"
];
$conn = sqlsrv_connect($server, $connectionInfo);
if ($conn) {
echo "Connection successful!";
} else {
print_r(sqlsrv_errors());
}
?>
In config/database.php
, use this:
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'encrypt' => true,
'trust_server_certificate' => true,
'options' => [
PDO::SQLSRV_ATTR_CONNECTION_POOLING => false,
"TrustServerCertificate" => true,
"Encrypt" => 1,
],
],
Installing and configuring the SQLSRV PHP extensions on Debian takes a few extra steps, but once done, your Laravel or PHP apps can connect to Microsoft SQL Server smoothly.
This works great on: