PHP function to get the subdomain of a URL

Damiano picture Damiano · Mar 13, 2011 · Viewed 134.7k times · Source

Is there a function in PHP to get the name of the subdomain?

In the following example I would like to get the "en" part of the URL:

en.example.com

Answer

Michael Deal picture Michael Deal · Jun 20, 2012

Here's a one line solution:

array_shift((explode('.', $_SERVER['HTTP_HOST'])));

Or using your example:

array_shift((explode('.', 'en.example.com')));

EDIT: Fixed "only variables should be passed by reference" by adding double parenthesis.


EDIT 2: Starting from PHP 5.4 you can simply do:

explode('.', 'en.example.com')[0];