编程语言
首页 > 编程语言> > php – 如何使用单个配置文件配置localhost和远程服务器

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

作者:互联网

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

标签:php,mysql,localhost,remote-server
来源: https://codeday.me/bug/20190623/1273323.html