function url(){
if(isset($_SERVER[\'HTTPS\'])){
$protocol = ($_SERVER[\'HTTPS\'] && $_SERVER[\'HTTPS\'] != \"off\") ? \"https\" : \"http\";
}
Shortest solution:
$domain = parse_url('http://google.com', PHP_URL_HOST);
First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com
$url= trim($url, '/');
If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
Get the parts of the URL.
$urlParts = parse_url($url);
Now remove www. from the URL
$domain = preg_replace('/^www\./', '', $urlParts['host']);
Your final domain without http and www is now stored in $domain variable.
Examples:
http://www.google.com => google.com
https://www.google.com => google.com
www.google.com => google.com
http://google.com => google.com
This works fine if you want the http protocol also since it could be http or https.
$domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
Use SERVER_NAME
.
echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
You could use PHP's parse_url()
function
function url($url) {
$result = parse_url($url);
return $result['scheme']."://".$result['host'];
}
Please try this:
$uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
$exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
$domain_name = $exploded_uri[1]; //$domain_name = 'example.com'
I hope this will help you.