Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Use Microsoft Entra authentication to connect to a Microsoft SQL target as a user, an application service principal, or a managed identity. Prefer a managed identity for an Azure application when its host provides one. For a workstation or another host, acquire an access token with an identity tool or library and pass it to the PHP extension.
Choose either the SQLSRV functions or the PDO_SQLSRV implementation of PHP Data Objects (PDO).
Authentication establishes the caller's identity. It doesn't grant access to a database automatically. You need both an authorized identity and a reachable SQL endpoint.
Check target support and permissions
| Target | Preparation |
|---|---|
| SQL Server | Use an instance configured for Microsoft Entra authentication, not an arbitrary SQL Server installation. The SQL administrator must configure the instance and grant the identity access. SQL Server Express LocalDB doesn't support this method. |
| Azure SQL Database | Configure a Microsoft Entra administrator and users for the selected database. Use <server>.database.windows.net and an explicit database. |
| Azure SQL Managed Instance | Configure Microsoft Entra authentication and the appropriate database access. Use its supplied endpoint, port, and network route. |
| SQL database in Microsoft Fabric | Microsoft Entra authentication is required. Copy the SQL database's connection details, not its SQL analytics endpoint. Check Fabric item access and database permissions. |
| Azure Synapse Analytics | Configure Microsoft Entra administration and access to the intended SQL pool or database. Check that pool's supported Transact-SQL (T-SQL) and permission model. |
| Warehouse in Microsoft Fabric | Microsoft Entra authentication is required. Copy the Warehouse connection details, select its database, and disable Multiple Active Result Sets (MARS). Check Fabric item/workspace access and SQL permissions. |
Grant the application identity the SQL permissions it needs to run queries. For Fabric, also grant access to the SQL database or Warehouse through a workspace role or item permissions. Azure subscription permissions are managed separately.
For Azure SQL setup, see Configure Microsoft Entra authentication. For the two Fabric products, use SQL database authentication and Warehouse security.
For a database that supports this provisioning syntax, an administrator can create a user for an existing Microsoft Entra principal:
CREATE USER [<principal-display-name>] FROM EXTERNAL PROVIDER;
Run provisioning as an authorized administrator in the intended database, not on every PHP request. The administrator might also need directory lookup permissions to resolve the principal. Duplicate display names need product-specific disambiguation; don't guess an identity from its display name. Grant only the required application permissions separately. For more information, see Create a database user.
The examples only read connection identity and database names. They don't create users or prove access to application tables.
Choose the identity and authentication method
The identity is the user or application granted database access. The authentication method is how ODBC or your application obtains proof of that identity.
| Method | Identity and credentials | Where it runs and who obtains the token |
|---|---|---|
Authentication=ActiveDirectoryMsi, system-assigned |
The host's system-assigned managed identity. Omit username and password. | A supported Azure host with that identity enabled and exposed to the PHP worker. ODBC calls its managed-identity endpoint. It doesn't use your Azure command-line interface (Azure CLI) sign-in. |
Authentication=ActiveDirectoryMsi, user-assigned |
A managed identity assigned to the host. Supply its selector as UID for SQLSRV or PDO's username argument; omit the password. |
The host must expose that assigned identity. Use its client ID for App Service or Container Instances; otherwise use the object ID as required by the ODBC host endpoint. Don't substitute the Azure resource ID. |
AccessToken |
A token representing an authorized user or application. Omit Authentication, username, and password. |
Windows, Linux, or macOS with a token-acquisition method supported by your identity tool or library. The application obtains and refreshes the token. |
Authentication=ActiveDirectoryIntegrated |
The process's integrated identity; omit username and password. | Windows uses its security credentials. Linux/macOS require an appropriate Kerberos ticket and federated identity configuration. A successful ordinary Windows SQL Server login doesn't prove this Entra path. |
Authentication=ActiveDirectoryServicePrincipal |
Application client ID as username and client secret as password. | Windows, Linux, or macOS with access to the identity provider. ODBC obtains the token. This method uses a secret and isn't passwordless. |
Authentication=ActiveDirectoryPassword |
Microsoft Entra username and password. | Deprecated. It can't satisfy an interactive multifactor authentication requirement. Don't choose it for a new application. |
Authentication=ActiveDirectoryInteractive |
Interactive user, with the username used to select the account. | ODBC's interactive method is Windows-only. PHP doesn't provide an interactive authentication callback or a device-code interface. For portable PHP programs and web workers, acquire a token externally instead of expecting a browser prompt inside a database call. |
| Device code, browser sign-in, workload identity federation, or certificate credentials through an external provider | The user or application that the provider authenticates. | Choose a provider that implements the flow, then use AccessToken. These aren't additional PHP Authentication keyword values. Follow your tenant's allowed sign-in and multifactor policies. |
Authentication=SqlPassword |
SQL username and password, not a Microsoft Entra identity. | Use the separate SQL authentication guide only on targets that support it. |
The PHP extensions forward the Authentication string to ODBC; they don't implement every identity flow themselves. For example, the released PHP connection builder special-cases managed identity and integrated authentication to avoid adding Trusted_Connection. For other modes, a missing or empty username can make it add that setting. Don't copy an ODBC interactive connection string with no username into PHP and assume it has the same behavior.
For source contracts, the released driver implements SQLSRV options, PDO data source name (DSN) handling, and shared credential and token handling. For ODBC configuration procedures, see Using Microsoft Entra ID with ODBC.
Prepare PHP and the connection
- Install the latest supported PHP extensions and Microsoft ODBC Driver. Verify the extensions in the actual worker. For more information, see Load the drivers.
- Copy the server and database from the target's connection details. Configure name resolution, network routes, firewall access, and certificate trust for that endpoint.
- Choose one method from the table. Grant that identity access to the target database. Have the administrator confirm the database user name that
USER_NAME()should return, including when access comes through a group. - Set the following variables in the PHP process's protected configuration. Don't populate unused credentials from an older authentication method.
| Variable | Value |
|---|---|
SQL_SERVER |
<server>,<port>, using the service's host name, not an address beginning with https://. |
SQL_DATABASE |
<database>, copied from the target. Store the raw name without ODBC braces. |
SQL_EXPECTED_USER |
The exact database principal name expected from USER_NAME(). This is an assertion, not an identity selector. |
SQL_IDENTITY_ID |
Only for a user-assigned managed identity: the host-specific identity selector. Leave unset for the system-assigned identity. |
SQL_ACCESS_TOKEN |
Only for the access-token examples: a current token for the SQL service. |
SQL_CLIENT_ID |
Only for the service-principal examples: the application's client ID. |
SQL_CLIENT_SECRET |
Only for the service-principal examples: the client secret's value, not its secret ID. |
Don't print these environment variables, a token-bearing PDO DSN, or a client secret. Use your hosting platform's secret facilities. A command-line environment isn't automatically inherited by a web worker.
Run the examples with -d zend.exception_ignore_args=1 as shown. This setting omits function arguments from exception traces, including token-bearing DSNs and credentials. Keep diagnostic output private.
Acquire an external token
For Azure public cloud, request the scope https://database.windows.net/.default with an identity library, or the resource https://database.windows.net/ with a tool that accepts a resource argument. This audience also applies to the Fabric SQL endpoints; don't use the Fabric management or Azure resource-management audience for a SQL connection.
For a local user test, sign in with Azure CLI to the intended tenant through your organization's approved flow. Replace <tenant-id> in az login --tenant <tenant-id> --allow-no-subscriptions with that tenant's ID. The --allow-no-subscriptions option also supports Fabric users who have no Azure subscription. If your organization permits device-code sign-in, use az login --tenant <tenant-id> --allow-no-subscriptions --use-device-code. These are external CLI sign-in flows, not PHP driver authentication callbacks.
With the CLI signed in, capture the token directly into the process environment. Run only the command for your shell, then run either PHP access-token example:
$env:SQL_ACCESS_TOKEN = az account get-access-token `
--resource https://database.windows.net/ --query accessToken -o tsv
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrEmpty($env:SQL_ACCESS_TOKEN)) {
throw 'SQL access token acquisition failed.'
}
SQL_ACCESS_TOKEN="$(az account get-access-token \
--resource https://database.windows.net/ --query accessToken -o tsv)" || exit 1
test -n "$SQL_ACCESS_TOKEN" || exit 1
export SQL_ACCESS_TOKEN
Don't run with shell tracing enabled. The commands assign the token instead of displaying it. The CLI identity must have database access; merely having an Azure subscription isn't sufficient. Don't ask users to paste tokens into source code or chat.
For unattended workloads, use managed identity or a suitable application credential/federation provider instead of depending on a developer's CLI cache. For nonpublic clouds, confirm the authority and SQL audience for that cloud. A token library handles provider-specific acquisition; neither PHP extension automatically invokes Azure CLI, performs device-code sign-in, or refreshes an externally supplied token.
Set connection options
Pass SQLSRV settings in the sqlsrv_connect() options array. For PDO_SQLSRV, use the DSN or constructor arguments shown in the table.
| Setting | SQLSRV | PDO_SQLSRV |
|---|---|---|
| Authentication method | Authentication option. |
Authentication in the DSN. |
| Username and password | UID and PWD options. |
Constructor username and password arguments, not PDO attributes. |
| User-assigned managed identity | UID option for the identity selector. Omit PWD. |
Constructor username argument for the identity selector. Pass null for the password. |
| External access token | AccessToken option. |
AccessToken in the DSN. Pass null for both constructor credentials. |
| Database | Database option. |
Database in the DSN. |
| MARS for Microsoft Fabric Warehouse | 'MultipleActiveResultSets' => false. |
MultipleActiveResultSets=false in the DSN. |
| Encryption and certificate validation | 'Encrypt' => true, 'TrustServerCertificate' => false. |
Encrypt=true;TrustServerCertificate=false in the DSN. |
| Connection timeout (seconds) | 'LoginTimeout' => 30. |
LoginTimeout=30 in the DSN. |
For UTF-8 character data, set SQLSRV's CharacterSet option to 'UTF-8'. For PDO_SQLSRV, set PDO::SQLSRV_ATTR_ENCODING to PDO::SQLSRV_ENCODING_UTF8 in the constructor options array.
If a SQLSRV connection or query fails, it returns false; retrieve the diagnostics immediately with sqlsrv_errors(). PDO construction throws PDOException on failure. Set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION in the constructor options array so subsequent operations also throw on failure.
AccessToken is mutually exclusive with Authentication and credentials, even when those settings contain empty strings. For SQLSRV, omit UID and PWD entirely. For PDO, omit constructor credentials or pass null, not ''. An empty token is an error. Pass only the token string extracted from the provider response, without Bearer , JSON wrapping, Base64 re-encoding, or manual UTF-16 conversion. The extension builds ODBC's access-token structure.
Database names and username/password strings use ODBC escaping in the programs. Supply raw values and escape once. The PDO AccessToken value is different: append the token string itself, without enclosing ODBC braces. Those braces become part of the token and cause authentication to fail. Keep server names and connection keywords under application control. For other settings, see Connection options.
Choose an example
Each program selects one authentication method directly. For PDO_SQLSRV, credentials belong in the constructor when the method requires them. The access-token program carries a secret in its DSN; never log it.
| Method | SQLSRV | PDO_SQLSRV |
|---|---|---|
| Managed identity | SQLSRV managed identity example. | PDO_SQLSRV managed identity example. |
| External access token | SQLSRV access token example. | PDO_SQLSRV access token example. |
| Service principal | SQLSRV service principal example. | PDO_SQLSRV service principal example. |
| Integrated authentication | SQLSRV integrated example. | PDO_SQLSRV integrated example. |
Every program checks the selected database and effective database user as UTF-8 PHP strings, then prints exactly:
Microsoft Entra database access verified.
When access comes through a group, or the administrator provisions a user under another name, use that expected database principal. A database-user assertion doesn't identify the token's tenant, object ID, or sign-in flow independently. Confirm those with your identity provider and administrator when testing identity selection.
Managed identity authentication
Use the system-assigned managed identity by leaving SQL_IDENTITY_ID unset. For a user-assigned identity, set SQL_IDENTITY_ID to the host-specific selector from the authentication-method table and make sure the identity is assigned to the host. The same programs support both cases. Test under the actual PHP worker, not a developer's terminal on a different machine.
ODBC obtains the token from the host endpoint. The PHP programs don't enable the identity, assign it to the host, or grant database permissions. Recreating a host can recreate its system-assigned identity with a different object ID; update the database mapping if necessary.
SQLSRV managed identity example
Save as entra-managed-identity-sqlsrv.php and run php -d zend.exception_ignore_args=1 entra-managed-identity-sqlsrv.php.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER'] 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) . '}';
$options = [
'Database' => $escape($config['SQL_DATABASE']),
'Authentication' => 'ActiveDirectoryMsi',
'Encrypt' => true,
'TrustServerCertificate' => false,
'LoginTimeout' => 30,
'MultipleActiveResultSets' => false,
'CharacterSet' => 'UTF-8',
];
$identity = getenv('SQL_IDENTITY_ID');
if ($identity !== false && $identity !== '') {
$options['UID'] = $escape($identity);
}
$conn = sqlsrv_connect($config['SQL_SERVER'], $options);
if ($conn === false) {
throw new RuntimeException(print_r(sqlsrv_errors(), true));
}
$stmt = null;
try {
$stmt = sqlsrv_query(
$conn,
'SELECT DB_NAME() AS DatabaseName, USER_NAME() AS DatabaseUser',
[],
['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['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
if (is_resource($stmt)) {
sqlsrv_free_stmt($stmt);
}
sqlsrv_close($conn);
}
PDO_SQLSRV managed identity example
Save as entra-managed-identity-pdo.php and run php -d zend.exception_ignore_args=1 entra-managed-identity-pdo.php. For the system-assigned identity, both constructor credentials are null.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER'] 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']);
$dsn = "sqlsrv:Server=$server;Database=$database;Encrypt=true;"
. "TrustServerCertificate=false;LoginTimeout=30;MultipleActiveResultSets=false;"
. "Authentication=ActiveDirectoryMsi";
$username = null;
$identity = getenv('SQL_IDENTITY_ID');
if ($identity !== false && $identity !== '') {
$username = $escape($identity);
}
$pdo = new PDO($dsn, $username, 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, USER_NAME() AS DatabaseUser',
[PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30]
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($row) || $row['DatabaseName'] !== $config['SQL_DATABASE']
|| $row['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
$stmt = null;
$pdo = null;
}
Access token authentication
Obtain a current token before opening a connection. A long-running worker must obtain another valid token when it opens a new connection after expiry. Neither a fixed environment variable nor retrying the same expired token refreshes it.
Releasing the PHP connection doesn't revoke the token. ODBC pooling can retain a physical connection, and token expiry isn't a guarantee that an already authenticated session immediately ends. Don't depend on connection pooling or expiry to implement sign-out or access revocation.
SQLSRV access token example
Save as entra-access-token-sqlsrv.php and run php -d zend.exception_ignore_args=1 entra-access-token-sqlsrv.php after acquiring SQL_ACCESS_TOKEN. The options omit Authentication, UID, and PWD.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER', 'SQL_ACCESS_TOKEN'] 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']),
'AccessToken' => $config['SQL_ACCESS_TOKEN'],
'Encrypt' => true,
'TrustServerCertificate' => false,
'LoginTimeout' => 30,
'MultipleActiveResultSets' => false,
'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, USER_NAME() AS DatabaseUser',
[],
['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['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
if (is_resource($stmt)) {
sqlsrv_free_stmt($stmt);
}
sqlsrv_close($conn);
}
PDO_SQLSRV access token example
Save as entra-access-token-pdo.php and run php -d zend.exception_ignore_args=1 entra-access-token-pdo.php. Append the raw token to the DSN without ODBC braces. Both constructor credentials are null.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER', 'SQL_ACCESS_TOKEN'] 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']);
$dsn = "sqlsrv:Server=$server;Database=$database;Encrypt=true;"
. "TrustServerCertificate=false;LoginTimeout=30;MultipleActiveResultSets=false;"
. "AccessToken=" . $config['SQL_ACCESS_TOKEN'];
$pdo = new PDO($dsn, 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, USER_NAME() AS DatabaseUser',
[PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30]
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($row) || $row['DatabaseName'] !== $config['SQL_DATABASE']
|| $row['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
$stmt = null;
$pdo = null;
}
After a local test, remove the token from your shell environment:
Remove-Item Env:\SQL_ACCESS_TOKEN
unset SQL_ACCESS_TOKEN
Don't enable ODBC tracing or dump connection configuration while carrying tokens unless your diagnostic procedure explicitly protects the resulting credentials.
Service principal authentication
Provision the application identity in the database. Set SQL_CLIENT_ID and SQL_CLIENT_SECRET through protected configuration, and plan secret rotation. A secret ID, application object ID, and client ID aren't interchangeable. A certificate-based or federated application credential belongs in an external token provider; it isn't a client secret for ActiveDirectoryServicePrincipal. After a local test, remove SQL_CLIENT_SECRET from that shell's environment. Don't delete or revoke a shared application credential as test cleanup.
SQLSRV service principal example
Save as entra-service-principal-sqlsrv.php and run php -d zend.exception_ignore_args=1 entra-service-principal-sqlsrv.php. Pass the client ID and secret value through UID and PWD.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER', 'SQL_CLIENT_ID', 'SQL_CLIENT_SECRET'] 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']),
'Authentication' => 'ActiveDirectoryServicePrincipal',
'UID' => $escape($config['SQL_CLIENT_ID']),
'PWD' => $escape($config['SQL_CLIENT_SECRET']),
'Encrypt' => true,
'TrustServerCertificate' => false,
'LoginTimeout' => 30,
'MultipleActiveResultSets' => false,
'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, USER_NAME() AS DatabaseUser',
[],
['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['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
if (is_resource($stmt)) {
sqlsrv_free_stmt($stmt);
}
sqlsrv_close($conn);
}
PDO_SQLSRV service principal example
Save as entra-service-principal-pdo.php and run php -d zend.exception_ignore_args=1 entra-service-principal-pdo.php. The client ID and secret value are constructor credentials, not PDO attributes.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER', 'SQL_CLIENT_ID', 'SQL_CLIENT_SECRET'] 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']);
$username = $escape($config['SQL_CLIENT_ID']);
$password = $escape($config['SQL_CLIENT_SECRET']);
$dsn = "sqlsrv:Server=$server;Database=$database;Encrypt=true;"
. "TrustServerCertificate=false;LoginTimeout=30;MultipleActiveResultSets=false;"
. "Authentication=ActiveDirectoryServicePrincipal";
$pdo = new PDO($dsn, $username, $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, USER_NAME() AS DatabaseUser',
[PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30]
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($row) || $row['DatabaseName'] !== $config['SQL_DATABASE']
|| $row['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
$stmt = null;
$pdo = null;
}
Integrated authentication
Configure the account, identity federation, and operating-system dependencies required by ODBC. On Linux and macOS, the PHP process needs access to a suitable Kerberos ticket; the driver doesn't renew it. A cloud-only account without that federation isn't a substitute. For more information, see ODBC integrated authentication and Federated account prerequisites.
With ActiveDirectoryIntegrated, ODBC can use ordinary Windows authentication when the server doesn't request federated authentication. Selecting this keyword or passing the database-user assertion alone doesn't prove Microsoft Entra token use. Confirm that the target is configured for Microsoft Entra authentication and check the identity provider's authentication records.
SQLSRV integrated example
Save as entra-integrated-sqlsrv.php and run php -d zend.exception_ignore_args=1 entra-integrated-sqlsrv.php under the configured process identity. Omit UID and PWD.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER'] 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']),
'Authentication' => 'ActiveDirectoryIntegrated',
'Encrypt' => true,
'TrustServerCertificate' => false,
'LoginTimeout' => 30,
'MultipleActiveResultSets' => false,
'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, USER_NAME() AS DatabaseUser',
[],
['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['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
if (is_resource($stmt)) {
sqlsrv_free_stmt($stmt);
}
sqlsrv_close($conn);
}
PDO_SQLSRV integrated example
Save as entra-integrated-pdo.php and run php -d zend.exception_ignore_args=1 entra-integrated-pdo.php. Both constructor credentials are null.
<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_EXPECTED_USER'] 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']);
$dsn = "sqlsrv:Server=$server;Database=$database;Encrypt=true;"
. "TrustServerCertificate=false;LoginTimeout=30;MultipleActiveResultSets=false;"
. "Authentication=ActiveDirectoryIntegrated";
$pdo = new PDO($dsn, 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, USER_NAME() AS DatabaseUser',
[PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30]
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($row) || $row['DatabaseName'] !== $config['SQL_DATABASE']
|| $row['DatabaseUser'] !== $config['SQL_EXPECTED_USER']) {
throw new RuntimeException('Unexpected database or Microsoft Entra database user.');
}
echo 'Microsoft Entra database access verified.', PHP_EOL;
} finally {
$stmt = null;
$pdo = null;
}
Deprecated password authentication
Important
The ActiveDirectoryPassword authentication option (Microsoft Entra ID password authentication) is deprecated in the Microsoft SQL drivers. This high-risk authentication flow is incompatible with mandatory Microsoft Entra multifactor authentication (MFA) and might not work in tenants where MFA is enforced. Plan to migrate to a different Microsoft Entra authentication method.
Microsoft Entra ID password authentication is based on the OAuth 2.0 Resource Owner Password Credentials (ROPC) grant, which allows an application to sign in the user by directly handling their password.
Microsoft recommends that you don't use the ROPC flow because it's incompatible with MFA. In most scenarios, more secure alternatives are available and recommended. This flow requires a high degree of trust in the application, and carries risks that aren't present in other flows. Use this flow only when more secure flows aren't viable. Microsoft is moving away from this high-risk authentication flow to protect users from malicious attacks. For more information, see Planning for mandatory multifactor authentication for Azure.
When a user is present at sign-in, use ActiveDirectoryInteractive or ActiveDirectoryIntegrated authentication so the audit trail attributes to the signed-in user and Conditional Access policies apply.
For unattended service-to-service scenarios, follow the Microsoft Entra service account guidance:
- If your application runs on Azure infrastructure, use ActiveDirectoryMSI (or ActiveDirectoryManagedIdentity in some drivers). Managed identities eliminate the overhead of maintaining and rotating secrets and certificates.
- If managed identity isn't available (for example, the application runs outside Azure), use ActiveDirectoryServicePrincipal. Where the driver supports it, prefer a client certificate over a client secret. With a certificate, the private key stays on the client and only a signed assertion is sent to Microsoft Entra to authenticate the client. If the key is stored in hardware (such as a TPM or HSM) or marked nonexportable, it can't be copied out as a string the way a client secret can.
- Don't use a Microsoft Entra user account as a service account.
If you're migrating existing ActiveDirectoryPassword code, the username and password belong in SQLSRV's UID/PWD options or PDO's constructor credentials, with Authentication=ActiveDirectoryPassword. These are Microsoft Entra credentials, not SQL login credentials. Don't change the value to SqlPassword while retaining the Entra credentials.
The complete programs deliberately exclude this deprecated method. Choose managed identity for a supported Azure workload or an external token provider for an approved user or application flow. An authentication method that needs an interactive challenge can't be repaired by repeatedly submitting the same password from a background worker.
Results, failures, and cleanup
SQLSRV returns connection and statement resources or false. Its fetch returns a row array, null at the end, or false on failure. Retrieve diagnostics immediately. PDO construction throws on failure regardless of error mode; subsequent database operations throw in the examples' explicit exception mode. PDO fetch returns an array or false at the end. SQL NULL within a result remains PHP null in both APIs.
The finally blocks release statement references before connection handles. They don't revoke a managed identity, delete a database user, clear a provider's token cache, or erase all copies of a secret from PHP memory. Don't retain a token-bearing DSN or credential array longer than the request or job needs it.
In web applications, catch failures at the request boundary and return a generic response. Keep detailed diagnostics in protected logs, and redact secrets. These command-line programs allow failures to terminate the process; don't expose their raw diagnostics through a website.
| Symptom | Check and action |
|---|---|
IMSSP reports incompatible access-token options |
Remove Authentication and all credential options. For PDO, use null, not empty-string constructor credentials. |
IMSSP reports an empty access token |
Stop before connecting and repair token acquisition. Don't replace a missing token with a placeholder or anonymous connection. |
"Login failed for user '<token-identified principal>'" or 28000 |
Check token tenant, SQL audience, expiry, identity, selected database, and database-user provisioning. A successfully issued token doesn't prove SQL authorization. |
AADSTS error or a required interactive challenge |
Follow the identity provider's error and tenant policy. Use an approved sign-in flow; don't weaken multifactor authentication or conditional access to make password code work. |
| Managed-identity endpoint unavailable or identity not found | Run on the intended host, enable/assign the identity, and check the host-specific selector. Don't substitute a developer token silently. |
| Service principal sign-in fails | Check client ID, secret value and expiry, tenant, and database principal. Never log the secret to inspect it. |
| Integrated sign-in fails on Linux/macOS | Check federation, ticket expiry, cache access, name resolution, and the worker's actual identity. An ordinary SQL Server Kerberos test doesn't prove Entra token acquisition. |
| Works with one PHP API but not the other | Check array option versus DSN versus constructor placement. A token in PDO's attributes array isn't the AccessToken DSN keyword. |
| Fabric connection fails or opens the wrong item | Recopy that item's connection details, check item/workspace access and database name, and disable MARS for Microsoft Fabric Warehouse. Don't substitute the SQL analytics endpoint for SQL database. |
08001, HYT00, or certificate errors |
Check network access, name resolution, host name, and certificate trust before changing the identity. Authentication and transport validation are separate. |
| Connection succeeds but a query is denied | Grant the database principal the required operation. Don't infer query rights from Azure or Fabric administration rights alone. |