Best way to get hostname with php

前端 未结 6 1976
别跟我提以往
别跟我提以往 2020-12-05 03:51

I have a php application that is installed on several servers and all of our developers laptops. I need a fast and reliable way to get the server\'s hostname or some other

相关标签:
6条回答
  • 2020-12-05 04:19

    php_uname but I am not sure what hostname you want the hostname of the client or server.

    plus you should use cookie based approach

    0 讨论(0)
  • 2020-12-05 04:22

    For PHP >= 5.3.0 use this:

    $hostname = gethostname();

    For PHP < 5.3.0 but >= 4.2.0 use this:

    $hostname = php_uname('n');

    For PHP < 4.2.0 use this:

    $hostname = getenv('HOSTNAME'); 
    if(!$hostname) $hostname = trim(`hostname`); 
    if(!$hostname) $hostname = exec('echo $HOSTNAME');
    if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 
    
    0 讨论(0)
  • 2020-12-05 04:22

    You could also use...

    $hostname = getenv('HTTP_HOST');
    
    0 讨论(0)
  • 2020-12-05 04:27

    The accepted answer gethostname() may infact give you inaccurate value as in my case

    gethostname()         = my-macbook-pro     (incorrect)
    $_SERVER['host_name'] = mysite.git         (correct)
    

    The value from gethostname() is obvsiously wrong. Be careful with it.

    Update as corrected by the comment

    Host name gives you computer name, not website name, my bad. My result on local machine is

    gethostname()         = my-macbook-pro     (which is my machine name)
    $_SERVER['host_name'] = mysite.git         (which is my website name)
    
    0 讨论(0)
  • 2020-12-05 04:30

    I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

    php_uname('n');
    
    gethostname();
    
    0 讨论(0)
  • 2020-12-05 04:38

    What about gethostname()?

    Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

    0 讨论(0)
提交回复
热议问题