How to Get a Domain Name in PHP
- 1). Create an empty variable called "$current_domain," or whatever you wish to call it. For example, you may use "$current_domain = '';" in your code.
- 2). Set $current_domain to the text of the HTTP host. The HTTP host is the part of the URL that comes after "http://" and it contains the domain name. It may also contain a "www," which you don't want. You may get the HTTP host from the $_SERVER global array. Try "$current_domain = $_SERVER['HTTP_HOST'];" as your code.
- 3). Make sure you have a domain name. If $current_domain is still empty, then the user's browser didn't request a URL with a domain name. This could mean that your script is being run on a command-line or other context besides in a web page.
- 4). Remove the "www." if it's there. Use preg_replace() to do this. Try "preg_replace('/^www\./i', '', 1);" as your code. The last parameter, with the value "1," doubly-ensures that you strip out only the first "www." from the text.
In a web context, "$current_domain" will now contain the domain name of the URL where your script is running. That is, it will contain the domain name of the current web page.
Get the Domain Name from the HTTP Host
Source...