PHP获取公网IP地址的程序代码

公网IP地址就是指外网IP地址了,就是在用户访问我们php页面时我们可以获到用户的IP地址了,而这个IP地址就叫做公网IP地址了,下面整理了两个函数一起看看.

方法1:获取客户端公网IP地址PHP,代码如下:

  1. /**
  2. * 获取真实IP地址
  3. */
  4. function get_real_ip(){
  5. if ( getenv( "HTTP_CLIENT_IP" ) && strcasecmp( getenv( "HTTP_CLIENT_IP" ), "unknown" ) ){
  6. $ip = getenv( "HTTP_CLIENT_IP" );
  7. }else if ( getenv( "HTTP_X_FORWARDED_FOR" ) && strcasecmp( getenv( "HTTP_X_FORWARDED_FOR" ), "unknown" ) ){
  8. $ip = getenv( "HTTP_X_FORWARDED_FOR" );
  9. }else if (getenv( "REMOTE_ADDR" ) && strcasecmp( getenv( "REMOTE_ADDR" ), "unknown" ) ){
  10. $ip = getenv( "REMOTE_ADDR" );
  11. }else if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) && $_SERVER[ 'REMOTE_ADDR' ]
  12. && strcasecmp( $_SERVER[ 'REMOTE_ADDR' ], "unknown" ) ){
  13. $ip = $_SERVER[ 'REMOTE_ADDR' ];
  14. }else{
  15. $ip = "unknown";
  16. }
  17. if ( strpos( $ip, ',' ) ){
  18. $ipArr = explode( ',', $ip );
  19. $ip = $ipArr[ 0 ];
  20. }
  21. return $ip;
  22. }

方法2:获取IP地址PHP,代码如下:

  1. function GetRealIP() {
  2. static $realip;
  3. if (isset($_SERVER)){
  4. if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
  5. $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  6. } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
  7. $realip = $_SERVER["HTTP_CLIENT_IP"];
  8. } else {
  9. $realip = $_SERVER["REMOTE_ADDR"];
  10. }
  11. } else {
  12. if (getenv("HTTP_X_FORWARDED_FOR")){
  13. $realip = getenv("HTTP_X_FORWARDED_FOR");
  14. } else if (getenv("HTTP_CLIENT_IP")) {
  15. $realip = getenv("HTTP_CLIENT_IP");
  16. } else {
  17. $realip = getenv("REMOTE_ADDR");
  18. } //开源软件:phpfensi.com
  19. }
  20. if (strpos($realip, ',') === false) {
  21. $sUserIp = $realip;
  22. } else {
  23. $arrUserIp = explode(',' , $realip);
  24. $sUserIp = $arrUserIp[0];
  25. }
  26. return $sUserIp;
  27. }

两段代码的效果是一样的,不信大家可以试一下了都非常的好用了.