How to identify server IP address in PHP

后端 未结 15 940
温柔的废话
温柔的废话 2020-11-29 23:52

How can I identify the server IP address in PHP?

相关标签:
15条回答
  • 2020-11-30 00:05

    This is what you could use as an adaptation of the above examples without worrying about curl installed on your server.

    <?php
          // create a new cURL resource
          $ch = curl_init ();
    
          // set URL and other appropriate options
          curl_setopt ($ch, CURLOPT_URL, "http://ipecho.net/plain");
          curl_setopt ($ch, CURLOPT_HEADER, 0);
          curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    
          // grab URL and pass it to the browser
    
          $ip = curl_exec ($ch);
          echo "The public ip for this server is: $ip";
          // close cURL resource, and free up system resources
          curl_close ($ch);
        ?>
    
    0 讨论(0)
  • 2020-11-30 00:09

    If you are using PHP in bash shell you can use:

    $server_name=exec('hostname');
    

    Because $_SERVER[] SERVER_ADDR, HTTP_HOST and SERVER_NAME are not set.

    0 讨论(0)
  • 2020-11-30 00:11

    I just created a simple script that will bring back the $_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR'] in IIS so you don't have to change every variable. Just paste this text in your php file that is included in every page.

    /** IIS IP Check **/
    if(!$_SERVER['SERVER_ADDR']){ $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR']; }
    if(!$_SERVER['REMOTE_ADDR']){ $_SERVER['REMOTE_ADDR'] = $_SERVER['LOCAL_ADDR']; }
    
    0 讨论(0)
  • 2020-11-30 00:12

    Check the $_SERVER array

    echo $_SERVER['SERVER_ADDR'];
    
    0 讨论(0)
  • 2020-11-30 00:13

    I came to this page looking for a way of getting my own ip address not the one of the remote machine connecting to me.

    This will not work for a windows machine.

    But in case someone searches for what I was looking for:

    #! /usr/bin/php
    <?php
    $my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
    echo $my_current_ip;
    

    (Shamelessly adapted from How to I get the primary IP address of the local machine on Linux and OS X?)

    0 讨论(0)
  • 2020-11-30 00:14

    If you are using PHP version 5.3 or higher you can do the following:

    $host= gethostname();
    $ip = gethostbyname($host);
    

    This works well when you are running a stand-alone script, not running through the web server.

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