Edit

SQL Server and Windows authentication from PHP

Download PHP driver

Choose how your PHP application authenticates to Microsoft SQL. SQL authentication uses a username and password managed by the SQL target. Windows integrated authentication uses the operating-system credentials available to the PHP process: Windows security credentials on Windows, or Kerberos credentials on Linux and macOS.

Use the SQLSRV functions or the PDO_SQLSRV implementation of PHP Data Objects (PDO). The examples show both APIs separately because they accept credentials and connection options in different places.

Prefer Microsoft Entra authentication for Azure and Fabric applications when available. That article covers managed identities, service principals, access tokens, and Microsoft Entra integrated authentication.

Check target support

Target SQL authentication Windows integrated authentication
SQL Server Enable SQL Server and Windows authentication mode, also called mixed mode. Windows-only mode rejects SQL logins. The server must recognize the Windows principal and grant it access. Linux-hosted SQL Server requires its own Active Directory configuration. Mixed mode isn't required.
SQL Server in Linux containers Use SQL authentication configured on the instance. If you connect through a port published on the container host, use that host name and published port. Configure Active Directory and Kerberos for SQL Server inside the container. Its service principal name (SPN) and keytab, a file containing Kerberos keys, must match the endpoint clients use. For more information, see Configure Kerberos for SQL Server containers.
SQL Server Express LocalDB Use its LocalDB guidance for supported authentication and local transport. Windows-only. Connect as an authorized local Windows identity. LocalDB doesn't support Microsoft Entra authentication.
Azure SQL Database Supported unless the logical server enforces Microsoft Entra-only authentication. Select the application database, including for a contained database user. Use Microsoft Entra authentication, not the default integrated settings in this article.
Azure SQL Managed Instance Supported unless the instance enforces Microsoft Entra-only authentication. Use the supplied endpoint and port. A separately configured service feature with Microsoft Entra and Kerberos prerequisites. For more information, see Windows authentication for Managed Instance.
SQL database in Microsoft Fabric Not supported. Use Microsoft Entra authentication and the SQL database connection details, not its SQL analytics endpoint.
Azure Synapse Analytics Supported for its SQL endpoints. Select the intended SQL pool or database and check its permission model. Use Microsoft Entra or SQL authentication, not the default Windows settings in this article.
Warehouse in Microsoft Fabric Not supported. Use Microsoft Entra authentication and disable Multiple Active Result Sets (MARS).

These are SQL-product requirements, not PHP extension settings. Changing Authentication doesn't enable an authentication method that the target disables.

Run PHP in a container

The container that runs PHP and a container that runs SQL Server are separate environments. Install the PHP extensions and ODBC dependencies inside the PHP container, even if they're already installed on its host. Configure name resolution, network access, and server certificate trust inside that container too. In SQL_SERVER, use the SQL endpoint reachable from the PHP container. For a SQL Server container with its own network address, use its reachable name and port rather than localhost.

Supply the examples' environment variables to the actual PHP worker through protected runtime configuration. Use your deployment platform's secret facilities for passwords and tokens. Don't embed credentials in a container image, Dockerfile, or committed deployment file. A successful connection from a terminal on the host doesn't prove that the PHP container has the same configuration or credentials.

For integrated authentication in a Linux PHP container, provide the Kerberos libraries, realm configuration, and an unexpired credential cache accessible to the PHP worker. If you select a cache with KRB5CCNAME, its path must exist inside the container and the worker must be able to read it. Protect any keytab and arrange ticket acquisition and renewal for that worker. Signing in on the host doesn't automatically provide these credentials to the container. For the client prerequisites, see Linux and macOS Kerberos credentials.

Choose an example

Choose your authentication method and PHP API. Each example is a complete command-line program that opens a connection, queries its database and login, and releases its resources. It doesn't create objects or read application tables.

Method SQLSRV PDO_SQLSRV
SQL username and password SQLSRV SQL authentication example. PDO_SQLSRV SQL authentication example.
Windows or Kerberos credentials SQLSRV Windows authentication example. PDO_SQLSRV Windows authentication example.

SQL authentication

Use a dedicated SQL login or contained database user when your application requires SQL credentials. The connection settings select the SQL identity. The examples display the database and login reported by the connection.

Prepare the login and PHP process

  1. Install a supported PHP extension and Microsoft ODBC Driver. Verify sqlsrv, or PDO and pdo_sqlsrv, in the process that runs the program. For more information, see Load the drivers.
  2. Ask your database administrator for an existing database and a dedicated application login or contained database user. For SQL Server, the administrator must enable mixed mode if necessary. Don't change an instance's authentication policy just to run a sample.
  3. For a server login, have the administrator map it to a user in the application database. A contained database user authenticates in that database without a separate server login. Grant only the application's required permissions. The examples require permission to connect and read the connection's own identity, not permission to create tables, administer the server, or read application tables.
  4. Confirm network access and a trusted certificate for the server host name. The examples explicitly request encryption and certificate validation. For connection setup, see Connect to Microsoft SQL from PHP.
  5. Supply these variables through protected configuration in the PHP process's environment.
Variable Value
SQL_SERVER <server>,<port>, using the host name covered by the certificate.
SQL_DATABASE <database>, an existing database the identity can open.
SQL_USER <user_id>, the SQL login or contained database username.
SQL_PASSWORD The actual password, supplied by your secret store or protected host configuration.

Don't copy angle-bracket placeholders literally. Don't place passwords in source control, a web-accessible text file, a command-line argument, or diagnostic output. A terminal and a web server can have different environment variables, PHP configurations, and service identities. Configure the environment of the actual worker.

Keep SQL_USER as the username required by the endpoint. The reported login name can differ, for example when an Azure SQL username includes a server qualifier.

Read settings from trusted configuration, not web request parameters. Store raw values in the environment. The programs escape database and credential values once for ODBC connection syntax: double closing braces and enclose each value in braces. This also keeps semicolons within a PDO data source name (DSN) value. Don't pre-escape the environment variables or trim a password; whitespace can be part of it.

Run the examples with -d zend.exception_ignore_args=1 as shown. This setting omits function arguments from exception traces, including credentials and connection strings. Keep diagnostic output private.

Authentication options

Purpose SQLSRV PDO_SQLSRV
Server First argument to sqlsrv_connect(). Server DSN keyword after the sqlsrv: prefix.
Database Database string in the options array. Database string in the DSN.
Username UID string in the options array. Second constructor argument.
Password PWD string in the options array. Third constructor argument.
Explicit SQL authentication Authentication => 'SqlPassword'. Authentication=SqlPassword in the DSN.
Encryption and certificate validation Encrypt => true, TrustServerCertificate => false. Encrypt=true;TrustServerCertificate=false in the DSN.
Connection timeout LoginTimeout => 30, in seconds. LoginTimeout=30 in the DSN.
Character results CharacterSet => 'UTF-8'. PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8 in the attributes array.
Error handling Check false and immediately retrieve sqlsrv_errors(). Set PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION. Construction throws on connection failure regardless of error mode.

Both extensions pass Authentication=SqlPassword to ODBC. If you omit Authentication but supply a nonempty username and password, the extensions also support SQL authentication. When the username is missing or empty, the extensions add Trusted_Connection unless you supply an access token or select managed-identity or integrated Entra mode. Without an explicit authentication mode, this requests integrated authentication. With Authentication=SqlPassword, the added setting conflicts with the selected mode. The examples reject a missing username before connecting. Neither extension prompts for a SQL password.

The released driver's shared connection code builds these ODBC settings. PDO's connection implementation handles the separate constructor credentials. For other settings, see Connection options.

SQLSRV SQL authentication example

Save this complete command-line program as sql-auth-sqlsrv.php. Run php -d zend.exception_ignore_args=1 sql-auth-sqlsrv.php after setting the four variables. It displays the selected database and current login without creating objects or changing data.

<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_USER', 'SQL_PASSWORD'] as $name) {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Set $name before running this example.");
    }
    $config[$name] = $value;
}
$escape = static fn(string $value): string => '{' . str_replace('}', '}}', $value) . '}';
$conn = sqlsrv_connect($config['SQL_SERVER'], [
    'Database' => $escape($config['SQL_DATABASE']),
    'UID' => $escape($config['SQL_USER']),
    'PWD' => $escape($config['SQL_PASSWORD']),
    'Authentication' => 'SqlPassword',
    'Encrypt' => true,
    'TrustServerCertificate' => false,
    'LoginTimeout' => 30,
    'CharacterSet' => 'UTF-8',
]);
if ($conn === false) {
    throw new RuntimeException(print_r(sqlsrv_errors(), true));
}

$stmt = null;
try {
    $stmt = sqlsrv_query(
        $conn,
        'SELECT DB_NAME() AS DatabaseName, SUSER_SNAME() AS LoginName',
        [],
        ['QueryTimeout' => 30]
    );
    if ($stmt === false) {
        throw new RuntimeException(print_r(sqlsrv_errors(), true));
    }
    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    if ($row === false) {
        throw new RuntimeException(print_r(sqlsrv_errors(), true));
    }
    if (!is_array($row)) {
        throw new RuntimeException('The identity query returned no row.');
    }
    echo 'Database: ', $row['DatabaseName'], PHP_EOL;
    echo 'Login: ', $row['LoginName'], PHP_EOL;
} finally {
    if (is_resource($stmt)) {
        sqlsrv_free_stmt($stmt);
    }
    sqlsrv_close($conn);
}

PDO_SQLSRV SQL authentication example

Save this separate program as sql-auth-pdo.php. Run php -d zend.exception_ignore_args=1 sql-auth-pdo.php with the same variables. Pass credentials as constructor arguments, not UID and PWD entries in the attributes array.

<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_USER', 'SQL_PASSWORD'] as $name) {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Set $name before running this example.");
    }
    $config[$name] = $value;
}
$escape = static fn(string $value): string => '{' . str_replace('}', '}}', $value) . '}';
$server = $config['SQL_SERVER'];
$database = $escape($config['SQL_DATABASE']);
$pdo = new PDO(
    "sqlsrv:Server=$server;Database=$database;Authentication=SqlPassword;"
    . "Encrypt=true;TrustServerCertificate=false;LoginTimeout=30",
    $escape($config['SQL_USER']),
    $escape($config['SQL_PASSWORD']),
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8,
    ]
);

$stmt = null;
try {
    $stmt = $pdo->prepare(
        'SELECT DB_NAME() AS DatabaseName, SUSER_SNAME() AS LoginName',
        [PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30]
    );
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!is_array($row)) {
        throw new RuntimeException('The identity query returned no row.');
    }
    echo 'Database: ', $row['DatabaseName'], PHP_EOL;
    echo 'Login: ', $row['LoginName'], PHP_EOL;
} finally {
    $stmt = null;
    $pdo = null;
}

Both programs print the connected database and login. For a database named appdb and a SQL login named appuser, the output is:

Database: appdb
Login: appuser

Check that the reported names match the database and identity you intend to use. SUSER_SNAME() returns the current security context, and neither program switches execution context. This function also supports Azure Synapse dedicated SQL pools, where ORIGINAL_LOGIN() isn't supported. A successful connection doesn't prove permission to read or write your application's tables. Test those operations separately as the application identity.

Troubleshoot SQL authentication

Check the stage that failed before changing credentials. Certificate and network failures can prevent the server from receiving a login attempt.

Symptom Check and action
28000, error 18456, or "Login failed" Check the target, mixed mode or Entra-only policy, login status, and secret version. Ask the administrator for the server-side failure reason. Don't retry a wrong password repeatedly or log it.
Error 4060 or "Cannot open database" Confirm SQL_DATABASE, the login-to-user mapping, and permission to connect. A valid server login doesn't grant access to every database.
A Windows or Kerberos error, or conflicting authentication settings, when you expected SQL authentication Check that SQL_USER is available and nonempty in the actual worker. Missing credentials can add an unintended Trusted_Connection setting.
Certificate validation failure Repair the host name or certificate trust configuration. It occurs before a successful login and isn't proof of an incorrect password. Don't disable certificate validation to fix credentials.
08001, HYT00, or a connection timeout Check name resolution, routing, firewall rules, port, and server availability before changing credentials. LoginTimeout isn't a query timeout.
IMSSP or an escaping error Supply raw environment values and apply ODBC escaping once. Confirm you aren't passing PDO attributes as DSN keywords.
The program reports an unexpected database or login Check SQL_SERVER, SQL_DATABASE, and SQL_USER against the intended endpoint and identity. The reported login can differ from the credential string in SQL_USER.
Connection succeeds but the application gets a permission error Grant the database user the specific required operation. Don't solve it by using an administrator account.

The SQL target validates credentials and permissions. ODBC owns network login and transport. The PHP extensions own option conversion, handles, and result conversion; PDO owns its exception and object contracts.

Windows authentication

The database connection normally uses the identity of the process that runs PHP, not the person visiting your website. A command-line connection working under your account doesn't prove that a web worker can connect under its service account. Check the identity in the actual deployment before granting access.

Windows integrated authentication and Microsoft Entra integrated authentication aren't interchangeable names. The PHP examples here omit Authentication, AccessToken, username, and password. The extensions then add Trusted_Connection=Yes to the underlying ODBC connection. For Microsoft Entra integrated authentication, explicitly select Authentication=ActiveDirectoryIntegrated as described in the Microsoft Entra article.

That keyword alone doesn't prove Microsoft Entra authentication. ODBC can use ordinary Windows authentication with ActiveDirectoryIntegrated when the SQL server doesn't request federated authentication. Confirm the target's configuration and the identity provider's authentication records before attributing a connection to Microsoft Entra ID.

Prepare the identity

Have the SQL administrator create a login for the Windows account or group that the application uses. Map that login to a user in the application database and grant the required permissions. Mixed mode isn't required for Windows authentication.

For example, the administrator can map an existing domain group to an existing SQL Server database with the following Transact-SQL (T-SQL). Replace the group and database with administrator-approved values. Don't run it as part of each application request.

CREATE LOGIN [CONTOSO\PhpAppReaders] FROM WINDOWS;
GO
USE [<database>];
GO
CREATE USER [CONTOSO\PhpAppReaders] FOR LOGIN [CONTOSO\PhpAppReaders];
GO

This mapping doesn't grant permission to application tables. Grant only the required object or schema permissions separately. Don't make a web worker a server administrator to solve a login error.

Windows process credentials

For command-line PHP, the account that starts php.exe supplies the credentials. For a service or web server, identify the account of the PHP worker. For example, an Internet Information Services (IIS) application pool identity and your interactive desktop account are different identities.

When a Windows virtual service account accesses a remote server, its network identity can be the computer account, such as CONTOSO\WEBHOST$, rather than the local service account name. Choose the intended service identity with your administrator and verify what SQL Server receives.

Windows Security Support Provider Interface (SSPI) negotiates authentication, commonly Kerberos or NT LAN Manager (NTLM), according to the host and domain configuration. Don't infer Kerberos from a successful Windows connection. For SQL Server, you can inspect CONNECTIONPROPERTY('auth_scheme') on your own connection to distinguish the negotiated mechanism.

If you intend to forward a website visitor's identity from the web server to another machine running SQL Server, you need an explicitly designed impersonation and delegation configuration. This additional network hop is often called the double hop. Enabling Windows authentication on the website doesn't by itself configure delegation. Prefer a dedicated application service identity when you don't need per-user database identities.

Linux and macOS Kerberos credentials

The ODBC driver uses the operating system's Kerberos libraries and credential cache. A local Linux or macOS username doesn't automatically become a Windows domain account, and the driver doesn't fall back to NTLM when Kerberos fails.

Before running PHP:

  • Have the administrator configure the Kerberos realm and Domain Name System (DNS) resolution. Confirm connectivity to the key distribution center (KDC), the service that issues Kerberos tickets. Keep the clocks synchronized.
  • Connect using the SQL server's fully qualified DNS name and configured port. The administrator must register the correct service principal name (SPN), typically MSSQLSvc/<server>:<port>, to the SQL Server service identity. Avoid substituting an Internet Protocol (IP) address or an unregistered DNS alias.
  • Obtain a ticket as the intended application principal. For an interactive test, kinit <principal> prompts for the principal's password without placing it in a command-line argument.
  • Run klist as the account that runs PHP and confirm an unexpired ticket in the cache that process uses. If you select a cache with KRB5CCNAME, provide that variable to the PHP worker too.
  • For a long-running service, arrange ticket acquisition and renewal through your operating-system service configuration. Protect any keytab, a file containing long-lived Kerberos keys, as a credential. Neither PHP extension nor ODBC renews your ticket automatically.

Run the examples under the same account and cache. Don't copy your interactive cache into a shared web directory. After an isolated interactive test, use kdestroy only for the test cache you created, not a shared user's or service's cache.

The released PHP driver's shared connection code requests integrated authentication on both platforms. ODBC and the operating system perform the security negotiation. For configuration procedures, see ODBC integrated authentication on Linux and macOS.

Configure the programs

Install and load the PHP extensions and their ODBC dependency. Configure network access and a trusted server certificate before testing remote SQL Server connections.

Set these variables in the actual PHP process. These programs don't require AdventureWorks or create any SQL objects.

Variable Value
SQL_SERVER <server>,<port>, using the DNS name configured for the service and certificate.
SQL_DATABASE <database>, accessible to the Windows principal.
SQL_EXPECTED_LOGIN The exact login name that your administrator expects SQL Server to report, for example CONTOSO\PhpApp. This isn't a credential or a way to select an identity.

Supply raw environment values. Both programs double closing braces in the database name and enclose the name in braces for ODBC syntax. Don't pre-escape SQL_DATABASE. PDO_SQLSRV uses a DSN string, while SQLSRV uses an options array.

Run the examples with -d zend.exception_ignore_args=1 as shown to omit connection arguments from exception traces. Keep diagnostic output private.

Setting SQLSRV PDO_SQLSRV
Select integrated authentication Omit UID, PWD, Authentication, and AccessToken. Pass null for both constructor credentials; omit Authentication and AccessToken from the DSN.
Select database Database string in the options array. Database string in the DSN.
Request encryption and certificate validation Encrypt => true, TrustServerCertificate => false. Encrypt=true;TrustServerCertificate=false.
Limit connection establishment LoginTimeout => 30, in seconds. LoginTimeout=30, in seconds.
Return UTF-8 character data CharacterSet => 'UTF-8'. PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8.
Limit query execution QueryTimeout => 30 statement option. PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30 statement attribute.

Don't add ODBC's Trusted_Connection keyword to the PHP options. The extensions supply it internally. Don't pass a domain username and password as SQLSRV UID/PWD or PDO constructor credentials to switch Windows identities; those arguments aren't Windows impersonation APIs. For the complete connection surface, see Connection options.

SQLSRV Windows authentication example

Save as integrated-sqlsrv.php and run php -d zend.exception_ignore_args=1 integrated-sqlsrv.php under the configured identity.

<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_LOGIN'] as $name) {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Set $name before running this example.");
    }
    $config[$name] = $value;
}
$database = '{' . str_replace('}', '}}', $config['SQL_DATABASE']) . '}';
$conn = sqlsrv_connect($config['SQL_SERVER'], [
    'Database' => $database,
    'Encrypt' => true,
    'TrustServerCertificate' => false,
    'LoginTimeout' => 30,
    'CharacterSet' => 'UTF-8',
]);
if ($conn === false) {
    throw new RuntimeException(print_r(sqlsrv_errors(), true));
}

$stmt = null;
try {
    $stmt = sqlsrv_query(
        $conn,
        'SELECT DB_NAME() AS DatabaseName, ORIGINAL_LOGIN() AS LoginName',
        [],
        ['QueryTimeout' => 30]
    );
    if ($stmt === false) {
        throw new RuntimeException(print_r(sqlsrv_errors(), true));
    }
    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    if ($row === false) {
        throw new RuntimeException(print_r(sqlsrv_errors(), true));
    }
    if (!is_array($row) || $row['DatabaseName'] !== $config['SQL_DATABASE']
        || $row['LoginName'] !== $config['SQL_EXPECTED_LOGIN']) {
        throw new RuntimeException('Unexpected database or Windows login.');
    }
    echo 'Integrated authentication verified.', PHP_EOL;
} finally {
    if (is_resource($stmt)) {
        sqlsrv_free_stmt($stmt);
    }
    sqlsrv_close($conn);
}

PDO_SQLSRV Windows authentication example

Save this separate program as integrated-pdo.php and run php -d zend.exception_ignore_args=1 integrated-pdo.php with the same identity and variables.

<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_LOGIN'] as $name) {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Set $name before running this example.");
    }
    $config[$name] = $value;
}
$server = $config['SQL_SERVER'];
$database = '{' . str_replace('}', '}}', $config['SQL_DATABASE']) . '}';
$pdo = new PDO(
    "sqlsrv:Server=$server;Database=$database;Encrypt=true;"
    . "TrustServerCertificate=false;LoginTimeout=30",
    null,
    null,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8,
    ]
);

$stmt = null;
try {
    $stmt = $pdo->prepare(
        'SELECT DB_NAME() AS DatabaseName, ORIGINAL_LOGIN() AS LoginName',
        [PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30]
    );
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!is_array($row) || $row['DatabaseName'] !== $config['SQL_DATABASE']
        || $row['LoginName'] !== $config['SQL_EXPECTED_LOGIN']) {
        throw new RuntimeException('Unexpected database or Windows login.');
    }
    echo 'Integrated authentication verified.', PHP_EOL;
} finally {
    $stmt = null;
    $pdo = null;
}

Both programs print exactly:

Integrated authentication verified.

The programs check database and original login names as exact UTF-8 PHP strings. They don't print the identity or prove table permissions. A database user granted access through a Windows group can have a different database-user name from the Windows login. ORIGINAL_LOGIN() checks the login that opened the session, rather than a subsequently impersonated database user.

Troubleshoot Windows authentication

Check the credentials available to the actual PHP worker, including its access to the intended Kerberos cache on Linux and macOS.

Symptom Check and action
The command-line program works but the web request fails Check the worker account, environment, and cache access. Grant access to the intended service identity, not the developer account.
"Login failed" for an unexpected computer or service account Check the actual network identity and administrator-approved login mapping. Changing SQL_EXPECTED_LOGIN doesn't change the caller's credentials.
"Login failed" for NT AUTHORITY\ANONYMOUS LOGON Check whether the worker's logon session has credentials for the remote server, or whether forwarding another identity requires delegation. Reporting the expected local Windows account doesn't prove remote access. Don't grant SQL access to the anonymous identity.
"Cannot generate SSPI context" or an SSPI failure Have the administrator check DNS, SPN registration and duplicates, domain trust, and clocks. Don't replace the server name with an IP address as a Kerberos fix.
"No Kerberos credentials available" or "Ticket expired" Acquire or renew a ticket in the PHP process's own cache. Check KRB5CCNAME and cache permissions under the worker account.
Failure only when forwarding a visitor's identity to another server Review impersonation and constrained delegation for the double hop. Don't broaden delegation permissions without an administrator's review.
Database access or table permission denied Check the login-to-user mapping and object permissions separately from authentication.
Certificate validation or network failure Correct trust, host name, route, or firewall configuration before diagnosing the identity.

Results, failures, and cleanup

SQLSRV returns connection and statement resources, or false on failure. sqlsrv_fetch_array() returns an array for a row, null at the end, and false on error. Retrieve sqlsrv_errors() immediately after the failed call. PDO returns connection and statement objects. Construction throws on connection failure; subsequent database operations throw PDOException in the examples' explicit exception mode. PDO fetch() returns an array for this fetch mode or false at the end.

SQL NULL values within either API's result remain PHP null. The queried names are character strings returned in UTF-8 by these programs; they aren't truncated to 32 characters.

The finally blocks release statements before connections, including after a failed result assertion. PDO statements can retain a reference to their connection, so release both. ODBC pooling can retain a physical connection after you release the PHP handle. For more information, see Connection pooling. Releasing a PHP connection doesn't revoke a Windows sign-in or destroy a Kerberos cache.

These are command-line programs. In a web application, catch failures at the request boundary and record details in protected logs. Return a generic failure response. Keep driver errors, exception traces, keytab paths, credential caches, and connection configuration out of web responses. Restrict access to command-line logs too.

Authentication establishes the caller's identity. The SQL target separately controls what that identity can do. Test the application's required queries as its intended identity.