繁体   English   中英

如何使用单个配置文件配置localhost和远程服务器

[英]How can I Configure localhost and remote server with single config file

我在localhost和远程服务器中使用不同的配置文件。 这让我非常不舒服,因为每次我需要更改服务器名称,密码和数据库名称。
是否有任何其他的单一配置方法连接localhost和远程服务器?

这是我的配置文件:

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
    }

    $conn->close();
?> 

您需要检查主机运行时间。

以下代码将在文件运行时检查主机。

根据主机,它将使用不同的凭据。

<?php
$host = $_SERVER['HTTP_HOST'];
if ($host == 'localhost') {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
}
else {
    $servername = "REMOTE_HOST";
    $username = "REMOTE_USERNAME";
    $password = "REMOTE_PASSWORD";
    $dbname = "REMOTE_DB";
}

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?> 

您可以检查存储当前主机的超全局$_SERVER数组的HTTP_HOST值。

最好使用strpos而不是比较。 您的HTTP_HOST可以具有指定的非默认端口,如localhost:8080 没关系,因为您的远程主机不太可能在其名称中包含localhost

<?php
    if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false)
    { 
        $servername = "localhost";
        $username = "username";
        $password = "password";
        $dbname = "myDB";
    } else {
        $servername = "10.11.12.13";
        $username = "username";
        $password = "P@$$w0rd";
        $dbname = "myDBName";            
    }

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $conn->close();
?> 

在虚拟主机中设置环境

    SetEnv environment {production/development}

所以你的虚拟主机可能如下所示:

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "/path/httpd"
    ServerName mysite.local
    ServerAlias mysite.local
    SetEnv environment production
</VirtualHost>

php代码:

<?php
if (getenv('environment') == 'production') {
    $servername = "localhost";
    $username = "production-username";
    $password = "production-password";
    $dbname = "myDB";
} else {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
}

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
$conn->close();

?> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM