Reputation: 707
I want to create a function on my functions.php that checks whether I'm on a local setup (url is http://macbook.local:5757/) or a live server (example.com).
Here is my code:
$server = $_SERVER["HTTP_HOST"];
if (strpos($server,'macbook') !== false) {
echo 'true ';
echo $server;
} else {
echo 'false ';
echo $server;
}
It outputs:
"false macbook.local:5757"
If I edit the code and put:
//$server = $_SERVER["HTTP_HOST"];
$server = "macbook.local:5757";
if (strpos($server,'macbook') !== false) {
echo 'true ';
echo $server;
} else {
echo 'false ';
echo $server;
}
I get: "true macbook.local:5757"
Why does the other one work when the other doesnt? They look like the same string. I'm probably missing something elementary here. I'm using a similar setup on wp-config.php to set database credentials depending on whether the site is local or live and it works there.
Thank you!
EDIT: If I use
var_dump($server);
it outputs:
false-string(17) "macbook.local:5757"
Upvotes: 0
Views: 3645
Reputation: 1
Mostly duplicate of: PHP: $_SERVER variables: $_SERVER['HTTP_HOST'] vs $_SERVER['SERVER_NAME']
As your code illustrates, those are not always equivalent. See:
https://www.php.net/manual/en/reserved.variables.server.php
Notice $_SERVER
is not always set; neither are its elements such as HTTP_HOST
. That's why you should check with isset($_SERVER['HTTP_HOST'])
first. strpos
is also advisable. Otherwise the exception handling might return FALSE
, not because the hostname is prod but because it's unknown, an empty string, or in a list. This won't be the result you want.
A small caveat: $_SERVER['HTTP_HOST']
is what appeared in the client's HTTP request, the Host:
header, such as "www.example.com:4443". Your browser sent that. That's not necessarily the same as $_SERVER['SERVER_NAME']
or other environment variables on the server. Depending on things such as load balancers and virtual hosts, the hostname that's in your back end config (Apache etc.) could be "www20" or "localhost" or whatever. Plus the port number could be elsewhere. So depending on what you're doing, you might need to change that, too.
Upvotes: 0