我想使用 PHP 获取 IP 表单浏览器地址栏。
Ip 是
https://192.168.40.32/example.com/
我只想要像192.168.40.32
这样的IP。
我正在使用这个函数来获取 IP:
echo $_SERVER['SERVER_NAME'];
但是我展示了双IP继续这样:
192.168.40.32192.168.40.32
那么我怎样才能获得知识产权呢?
我认为这就是你想要的:
echo $_SERVER['REMOTE_ADDR'];
你也应该看看这里
获取 IP 的另一种方法是使用 explode
$url='https://192.168.40.32/example.com/';
$first=explode('//',$url);
$string=explode('/',$first[1]);
var_dump($string[0]); //192.168.40.32
try this
<?php
$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
?>
这是一个尝试在 url 栏中查找 ip 地址的函数,如果它在那里没有任何 ip,它将在 $_SERVER 数组中查找 IP 地址。
<?php
function uriIP() {
$s = $_SERVER['HTTP_HOST'];
//Look for a number with dots made like: ***.*.**.*** ex.
preg_match('/[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}/i', $s, $matches);
if (!isset($matches[0])) {
//Check to see if we have an IP address stored in the $_SERVER array
if ($_SERVER['SERVER_ADDR']) {
//Return the value if we find any (true)
return $_SERVER['SERVER_ADDR'];
} else {
//nothing found here, return false
return false;
}
//if we found a match in our regex, return the first match:
} else {
return $matches[0];
}
}
print_r(uriIP());
如果 IP 地址在字符串中重复,最好使用正则表达式。preg_match
<?php
//Example - 1
$server_name='https://192.168.40.32/example.com/192.168.40.33/192.168.40.34'; //$_SERVER['SERVER_NAME'];
$pattern = '/'d{1,3}'.'d{1,3}'.'d{1,3}'.'d{1,3}/'; //regex pattern
preg_match($pattern, $server_name, $ip_data); //get the correct ip address
$ip = $ip_data[0]; //its an array
print_r($ip); // display to see result.
?>
检查结果:https://eval.in/534366
您可以使用获取IP地址;
$_SERVER['REMOTE_ADDR']
<?php
//Example - 2
$url = $_SERVER['REMOTE_ADDR']; //get the ip address
$my_valid_ip = filter_var($url, FILTER_VALIDATE_IP); // check the ip address if its valid
print_r($my_valid_ip); //display to see result.
?>