Tutorial – PHP Get Main Domain

I was on a recent PHP project and found the need to get the domain name of the app I was building for. When I did some research I found that the main method I was using could become unreliable based on how a server is configured.

As it turns out $_SERVER['HTTP_HOST'] might not be set. Since I’m building an application that has the requirement to run on many different servers, I had to make sure that I had a fallback if $_SERVER['HTTP_HOST'] was not set.

To solve for this problem, we need to provide a fallback method. So the solution for the application I’m building ended up turning out like this.

$requestDomain = ($_SERVER['HTTP_HOST']) 
? $_SERVER['HTTP_HOST']
: $_SERVER['SERVER_NAME'];

Author: Joshua Johnson

My name is Joshua Johnson and I am the founder of UA1 Labs. I am passionate about helping other developers to become successful in their paths. When I started developing software, I didn't have many resources to help me out. UA1 Labs is my way of giving back to all those who helped me.

Leave a Reply

Your email address will not be published. Required fields are marked *