How can I get the IP address and port of a client with PHP?

◇◆丶佛笑我妖孽 提交于 2019-12-25 08:45:02

问题


How do I get the IP and port of a client with PHP?

I tried the script below but it only gives me the IP address.

<?php print $_SERVER['REMOTE_ADDR']; ?>

回答1:


Port is defined in http server (Apache or other and mostly it is 80 or 443)

The PHP $_SERVER variables can be checked at this link.

I am sure that 'REMOTE_ADDR' returns the IP address from which the user is viewing the current page.

But if your server is behind NAT:

If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.

// in place of $_SERVER['REMOTE_ADDR']
$_SERVER['HTTP_X_FORWARDED_FOR']

//  in place of $_SERVER['SERVER_NAME']
$_SERVER['HTTP_X_FORWARDED_HOST'] && $_SERVER['HTTP_X_FORWARDED_SERVER']



回答2:


To get the port of the connected device you can use $_SERVER['REMOTE_PORT']

$ipAddress = $_SERVER['REMOTE_ADDR'];
$port      = $_SERVER['REMOTE_PORT'];



回答3:


Try this:

if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['REMOTE_ADDR'];
}
else {
    $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}


来源:https://stackoverflow.com/questions/23251868/how-can-i-get-the-ip-address-and-port-of-a-client-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!