如何使用单个配置文件配置本地主机和远程服务器

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();
?> 

您可以检查存储当前主机的超全局 $_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();
?> 

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

以下代码将在文件 运行s.

时检查主机

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

<?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();
?> 

在你的虚拟主机环境中设置

    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();

?>