【问题标题】:IIS PHP use connection string from web.configIIS PHP 使用来自 web.config 的连接字符串
【发布时间】:2012-10-26 08:14:18
【问题描述】:

我们使用在 connect.php 中定义的字符串,但现在我们有一些启用了 silverilght 的服务,它们利用 IIS 中的 web.config 作为它们的连接字符串。

那么,与其在两个地方都有连接字符串,我可以从 PHP 访问 web.config 中的那个吗?这也将使最终用户更容易进行更改。

【问题讨论】:

    标签: php iis connection-string


    【解决方案1】:

    我知道这是一个非常古老的线程,但最近我遇到了类似的问题。我只是将我的解决方案分享给需要它的人。它 100% 达到了我的目的,希望它对你也有帮助。

    在我的 web.config 连接字符串节点看起来像:

    <connectionStrings>
        <add name="sqlDB" connectionString="Server=xxx.xxx.xxx.xxx; Database=db_name; User Id=sqlserver_user_name; password=sqlserver_password;Max Pool Size=2000;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    我编写了以下 PHP 代码来检索 sql server 连接信息以在 PHP 中使用它

    <?php
        // start get connection string from web.config
        $xml =  simplexml_load_file("../Web.config") or die("Error: Cannot create object"); 
        //in my case web.config is in previous directory
        $array = json_decode(json_encode((array) $xml), 1);
    
        $server = "";
        $database = "";
        $user = "";
        $password = "";
    
        $fullString = ($xml->connectionStrings->add[0]["connectionString"]);
    
        $strArr = explode(";", $fullString);
    
        $arrCount = count($strArr);
        $connArr[]="";
        for($x=0;$x<$arrCount-1;$x++){
            $aS = explode("=",$strArr[$x]);
            $connArr+=array(strtolower(trim($aS[0])) => trim($aS[1]));
        }
        $server = $connArr["server"];
        $database = $connArr["database"];
        $user = $connArr["user id"];
        $password = $connArr["password"];
        // end get connection string from web.config
    
        $connectionInfo = array( "UID"=>$user,                            
                                 "PWD"=>$password,                            
                                 "Database"=>$database,
                                 "CharacterSet" => "UTF-8"); 
    
        /* Connect using SQL Server Authentication. */  
        $conn = sqlsrv_connect( $server, $connectionInfo); 
    ?>
    

    仅供参考:在我的例子中,web.config 和 php 文件位于同一个域和同一个根目录下。如果您在跨域环境中工作,您应该首先考虑从远程位置读取 web.config,但出于安全原因,这不是一个明智的决定。

    谢谢

    【讨论】:

    • 很高兴听到这个 Burgi。
    【解决方案2】:

    是的,你可以。

    • 确保 Web 服务器进程有权访问该文件。您可以输入一个可供网络服务器进程访问的链接。
    • web.config 只是一个 xml 文件。您可以使用我提供的 sn-p 作为示例或基础来读取文件并根据需要进行调整。

    片段:

    public function Load( $xmlfile )
    {
      if ( is_readable( $xmlfile ) ) {
        $config = $this->xml2array( simplexml_load_file( $xmlfile ) );
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-15
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多