PHP获取公网IP地址的程序代码
公网IP地址就是指外网IP地址了,就是在用户访问我们php页面时我们可以获到用户的IP地址了,而这个IP地址就叫做公网IP地址了,下面整理了两个函数一起看看.
方法1:获取客户端公网IP地址PHP,代码如下:
- /**
- * 获取真实IP地址
- */
- function get_real_ip(){
- if ( getenv( "HTTP_CLIENT_IP" ) && strcasecmp( getenv( "HTTP_CLIENT_IP" ), "unknown" ) ){
- $ip = getenv( "HTTP_CLIENT_IP" );
- }else if ( getenv( "HTTP_X_FORWARDED_FOR" ) && strcasecmp( getenv( "HTTP_X_FORWARDED_FOR" ), "unknown" ) ){
- $ip = getenv( "HTTP_X_FORWARDED_FOR" );
- }else if (getenv( "REMOTE_ADDR" ) && strcasecmp( getenv( "REMOTE_ADDR" ), "unknown" ) ){
- $ip = getenv( "REMOTE_ADDR" );
- }else if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) && $_SERVER[ 'REMOTE_ADDR' ]
- && strcasecmp( $_SERVER[ 'REMOTE_ADDR' ], "unknown" ) ){
- $ip = $_SERVER[ 'REMOTE_ADDR' ];
- }else{
- $ip = "unknown";
- }
- if ( strpos( $ip, ',' ) ){
- $ipArr = explode( ',', $ip );
- $ip = $ipArr[ 0 ];
- }
- return $ip;
- }
方法2:获取IP地址PHP,代码如下:
- function GetRealIP() {
- static $realip;
- if (isset($_SERVER)){
- if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
- $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
- } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
- $realip = $_SERVER["HTTP_CLIENT_IP"];
- } else {
- $realip = $_SERVER["REMOTE_ADDR"];
- }
- } else {
- if (getenv("HTTP_X_FORWARDED_FOR")){
- $realip = getenv("HTTP_X_FORWARDED_FOR");
- } else if (getenv("HTTP_CLIENT_IP")) {
- $realip = getenv("HTTP_CLIENT_IP");
- } else {
- $realip = getenv("REMOTE_ADDR");
- } //开源软件:phpfensi.com
- }
- if (strpos($realip, ',') === false) {
- $sUserIp = $realip;
- } else {
- $arrUserIp = explode(',' , $realip);
- $sUserIp = $arrUserIp[0];
- }
- return $sUserIp;
- }
两段代码的效果是一样的,不信大家可以试一下了都非常的好用了.