-1

i want only domain name without sub domain and path URL.

Example :

URL loading in browser : https://www.example.com/something. I want only example.com

I tried echo $_SERVER['HTTP_HOST']; and echo $_SERVER['SERVER_NAME']; but the output is www.example.com but it want example.com as output.

What to use?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Stellan Coder
  • 323
  • 1
  • 11
  • This isn't straightforward in terms of steps to get the exact domain name. Check https://stackoverflow.com/a/14210490/4964822 – nice_dev Jan 07 '22 at 18:19
  • 1
    `preg_replace('/^www\./','',$_SERVER['HTTP_HOST'])` ? – Dirk J. Faber Jan 07 '22 at 18:28
  • @DirkJ.Faber Your code works but it only work for `www` not for all `subdomain.example.com` and every time i have to edit. i am not lazy to edit sub domains in code but there is hundreds of subdomain. how we can pick only domain name from `anything.example.com` – Stellan Coder Jan 07 '22 at 18:29
  • 1
    @DirkJ.Faber I think SERVER_NAME instead of HTTP_POST because HTTP_POST add port into url if not 80 or 443 port – Jerson Jan 07 '22 at 18:29
  • You could use some other regex, for example `/^([^.]+)/`, but there are different ways to solve this. – Dirk J. Faber Jan 07 '22 at 18:35
  • 1
    You can do preg_replace('/^[^.]*\.(?=\w+\.\w+$)/','',$_SERVER['SERVER_NAME']) – Jerson Jan 07 '22 at 18:41
  • `$host = preg_replace('/^[^.]*\.(?=\w+\.\w+$)/','',$_SERVER['SERVER_NAME']);` for own reference – Stellan Coder Jan 07 '22 at 19:01

1 Answers1

1

I would make a check for the existing of "www." in the beginning of the string, and if the string starts with "www." I would remove it.

Example:

$domain = substr($_SERVER['SERVER_NAME'],0,4) === 'www.' ? substr($_SERVER['SERVER_NAME'],4) : $_SERVER['SERVER_NAME'];
echo $domain;
thephper
  • 2,342
  • 22
  • 21
  • Your code works but it only work for `www` not for all `subdomain.example.com` and every time i have to edit. i am not lazy to edit sub domains in code but there is hundreds of subdomain. how we can pick only domain name from `anything.example.com` – Stellan Coder Jan 07 '22 at 18:23
  • Ah okay - try take a look at this answer here: https://stackoverflow.com/questions/2679618/get-domain-name-not-subdomain-in-php . It does what you want and only return the main domain without subdomains. – thephper Jan 07 '22 at 18:37