How to get a server’s hostname in PHP

The hostname of your server or local system is an easy way to determine which
environment you are working with, either local or production. Prior to PHP 5.3
you would need to utilize the php_uname() function and with 5.3+ there is a
built-in function for getting the hostname:

pre-5.3

$hostname = php_uname('n'

5.3+

$hostname = gethostname

Once you have the hostname, you can do a simple conditional to determine if
you are working on running code in your local development environment or out
on your server:

if ($hostname == 'production') {
    // Production stuff
} else {
    // Local stuff
}

If you have multiple regions, you could change up the if/else for a switch
statement:

switch ($hostname) {
    case 'production':
        // Production stuff
        break

    case 'staging':
        // Staging stuff
        break

    case 'development':
    case 'local':
    default:
        // Local stuff
        break
}

What sort of logic would you need to run on a per environment basis? Well,
perhaps you use different database credentials in each environment, or you
want to pre-populate the database in your local or staging environments. It’s
really up to you and the possibilities are endless!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.