无法使用 Windows 身份验证从 PHP 连接 SQL Server

无法使用 Windows 身份验证从 PHP 连接 SQL Server

我正在尝试使用适用于 PHP 的 SQL Server 驱动程序(即 SQLSRV-5.9)从 PHP-8.0(托管在 IIS-10 本地主机上)连接到 MS-SQL Server。从 PHP 页面连接时,如果我使用 SQL Server 身份验证,它会立即连接。但是,在使用 Windows 身份验证时,它会在浏览器中抛出一个错误,提示:

Connection could not be established.
Array ( [0] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 18456 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. ) [1] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 18456 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'NT AUTHORITY\IUSR'. ) )

我的环境是 Windows 10 Pro,版本 21H2,64 位。在我的 SQL Server 中,Windows 身份验证和 SQL Server 身份验证都已启用,并且我能够通过 SQL Server Management Studio 使用它们连接到服务器。那么是什么阻止我的 PHP 代码使用 Windows 身份验证连接到服务器?PHP 和 SQL Sever 都在同一台 PC 上。我做错了什么?由于我是 PHP 新手,您能用一个简单的例子来解释一下吗?

我的 connect-db.php 代码如下。请注意我如何将连接字符串用于 Windows 和 SQL Server 身份验证。

?php
    $serverName = "(local)";    // Optionally use port number (1433 by default).
    $connectionString = array("Database"=>"TestDB");    // Windows Authentication connection string.
    // $connectionString = array("UID"=>"sa","PWD"=>"sa","Database"=>"TestDB");    // SQL Server Authentication connection string.
    $conn = sqlsrv_connect($serverName, $connectionString); // Connect to the server.

    if($conn === false) {
        echo "Connection could not be established.<br/>";
        die(print_r(sqlsrv_errors(), true));
    } else {
        echo "Connection established successfuly.<br/>";
    }

    sqlsrv_close($conn);    // Close connection resources.
?>

感谢致敬!

答案1

问题在于 NT AUTHORITY\IUSR 在 SQL Server 中没有任何登录名。与 .Net 应用程序不同,IIS 不使用 SQL Server 安装附带的默认 Windows 身份验证登录名。它使用 NT AUTHORITY\IUSR,我并不知道这一点。但 NT AUTHORITY\IUSR 在 SQL Server 中没有为其创建任何默认登录名或 DB 用户。您需要明确创建它们。创建它们并赋予它们相应的数据库权限解决了这个问题。现在我可以使用 SQL Server 身份验证从 PHP 登录。希望这对后人有所帮助。

相关内容