我想获取我的计算机的IP地址。我的整个代码是
<?php
echo $_SERVER['REMOTE_ADDR'];
当我尝试在终端php -f index.php
中运行文件时,出现此错误PHP Notice: Undefined index: HTTP_X_FORWARDED_FOR in /home/orpheus/Practice_dev/requestMicroservice/index.php on line 4
我也在网站上找到了此代码,并认为该代码可以获取我的IP地址
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;
}
但是当我在终端中运行文件时,会得到未定义的索引:REMOTE_ADDR。
我在做什么错?