How to get my ip adress in php?

I just started the api projects and I’m trying to get my ip adress but with my code I keep getting errors showing undefined.

First I tried this


   echo $_SERVER['REMOTE_ADDR'];

and ran the file in my terminal with this php -f index.php and I get this errorPHP Notice: Undefined index: HTTP_X_FORWARDED_FOR in /home/orpheus/Practice_dev/requestMicroservice/index.php on line 4

I found this function on a website that is supposed to return my ip adress

function get_ip() {
  //Just get the headers if we can or else use the SERVER global.
  if ( function_exists( 'apache_request_headers' ) ) {
    $headers = apache_request_headers();
  } else {
    $headers = $_SERVER;
  //Get the forwarded IP if it exists.
  if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
    $the_ip = $headers['X-Forwarded-For'];
  } elseif ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
    $the_ip = $headers['HTTP_X_FORWARDED_FOR'];
  } else {

    $the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );
  return $the_ip;

but I got Undefined index: REMOTE_ADDR in my console from that function. I’m not sure what I’m doing wrong here and would appreciate help.

If you run this code on a webserver, it will work.

thanks I didn’t consider that.