MySQL connection string for multiple servers in PHP


This is something that I started doing recently that I have found really helpful. Whenever I have a MySQL include file for a web development project, I set it up so it will work on both my local dev server and the live website. I accomplish this by checking to see where the file is being loaded from – if it is being loaded from the web server, you just connect to localhost; if it is being loaded somewhere else, it will use the domain name to access the database server.

// define your settings
$domain = "example.com";
$user = "dblogin";
$pass = "dbpassword";
$schema = "dbname";

// check to see where this is being loaded from
if ($_SERVER['HTTP_HOST'] == "$domain" || $_SERVER['HTTP_HOST'] == "www.$domain") {
	// if loaded off website, connect to localhost
	$link = mysqli_connect("localhost", $user, $pass, $schema) or die(mysqli_error());
} else {
	// otherwise you will need to access it remotely
	$link = mysqli_connect($domain, $user, $pass, $schema) or die(mysqli_error());
}

// check your connection
if (mysqli_connect_errno()) {
	printf("Connect failed: %s\n", mysqli_connect_error());
	exit();
}

This works great because you have have the exact same files on both servers, when you deploy changes to the site you don’t need to worry about removing your development server info.

  1. No comments yet.
(will not be published)
Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 314 bad guys.


  1. No trackbacks yet.