如何在PHP中获取客户端IP地址? [英] How to get the client IP address in PHP?

查看:217
本文介绍了如何在PHP中获取客户端IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PHP获取客户端IP地址?

How can I get the client IP address using PHP?

我想保留通过他/她的IP地址登录我的网站的用户的记录。 / p>

I want to keep record of the user who logged into my website through his/her IP address.

推荐答案

无论您做什么,请确保不信任从客户端发送的数据。 $ _ SERVER ['REMOTE_ADDR'] 包含连接方的真实IP地址。这是您可以找到的最可靠的价值。

Whatever you do, make sure not to trust data sent from the client. $_SERVER['REMOTE_ADDR'] contains the real IP address of the connecting party. That is the most reliable value you can find.

但是,它们可能在代理服务器的后面,在这种情况下,代理可能设置了 $ _ SERVER ['HTTP_X_FORWARDED_FOR'] ,但这个值很容易被欺骗。例如,它可以由没有代理的人设置,或者IP可以是来自代理服务器后面的LAN的内部IP。

However, they can be behind a proxy server in which case the proxy may have set the $_SERVER['HTTP_X_FORWARDED_FOR'], but this value is easily spoofed. For example, it can be set by someone without a proxy, or the IP can be an internal IP from the LAN behind the proxy.

这意味着如果你要去要保存 $ _ SERVER ['HTTP_X_FORWARDED_FOR'] ,请确保您保存 $ _ SERVER ['REMOTE_ADDR'] 值。例如。通过将两个值保存在数据库中的不同字段中。

This means that if you are going to save the $_SERVER['HTTP_X_FORWARDED_FOR'], make sure you also save the $_SERVER['REMOTE_ADDR'] value. E.g. by saving both values in different fields in your database.

如果要将IP作为字符串保存到数据库,请确保至少有空格<强> 45个字符。 IPv6 在这里停留,这些地址比旧的IPv4地址大。

If you are going to save the IP to a database as a string, make sure you have space for at least 45 characters. IPv6 is here to stay and those addresses are larger than the older IPv4 addresses.

(请注意,IPv6通常最多使用39个字符,但也有一个特殊的 IPv4地址的IPv6符号,其格式最多可以达到45个字符,所以如果你知道你在做什么,你可以使用39个字符,但是如果你只想设置并忘记它,使用45)。

(Note that IPv6 usually uses 39 characters at most but there is also a special IPv6 notation for IPv4 addresses which in its full form can be up to 45 characters. So if you know what you are doing you can use 39 characters, but if you just want to set and forget it, use 45).

这篇关于如何在PHP中获取客户端IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆