我在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();
?>
答案 0 :(得分:2)
您需要检查主机运行时间。
以下代码将在文件运行时检查主机。
根据主机的不同,它将使用不同的凭据。
<?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();
?>
答案 1 :(得分:1)
您可以检查存储当前主机的超全局$_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();
?>
答案 2 :(得分:1)
在虚拟主机中设置环境
//set the sync context
var thisSyncContext = new SynchronizationContext();
SynchronizationContext.SetSynchronizationContext(thisSyncContext);
thisSyncContext.Post(cb => {
var ctx = SynchronizationContext.Current; //<-- this is null
var equals = thisSyncContext.Equals(ctx); //<-- this is false
},null);
thisSyncContext.Send(cb => {
var ctx = SynchronizationContext.Current; //<-- this is not null
var equals = thisSyncContext.Equals(ctx); //<-- this is true
}, null);
因此,您的虚拟主机可能如下所示:
SetEnv environment {production/development}
php代码:
<VirtualHost *:80>
ServerAdmin webmaster@dummy-host2.example.com
DocumentRoot "/path/httpd"
ServerName mysite.local
ServerAlias mysite.local
SetEnv environment production
</VirtualHost>