Skip to content

Instantly share code, notes, and snippets.

@soderlind
Last active July 12, 2021 09:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soderlind/3d620201fced5631247edff7b5485c9a to your computer and use it in GitHub Desktop.
Save soderlind/3d620201fced5631247edff7b5485c9a to your computer and use it in GitHub Desktop.
PHP, Get IP behind trusted proxy
<?php
/**
* Inspired by https://raw.githubusercontent.com/zendframework/zend-http/master/src/PhpEnvironment/RemoteAddress.php
*/
//PHP 5.6
function get_ip( $trusted_proxies = [] ) {
if ( ! empty( $trusted_proxies ) && isset( $_SERVER['REMOTE_ADDR'] ) && ! in_array( $_SERVER['REMOTE_ADDR'], $trusted_proxies ) ) {
if ( isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} elseif ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif ( isset( $_SERVER['HTTP_X_FORWARDED'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED'];
} elseif ( isset( $_SERVER['HTTP_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_FORWARDED_FOR'];
} else ( isset( $_SERVER['HTTP_FORWARDED'] ) ) {
$ip = $_SERVER['HTTP_FORWARDED'];
}
return ( ! empty( $ip ) ) ? array_pop( array_diff( array_map( 'trim', explode( ',', $ip ) ), $trusted_proxies ) ) : 'unknown';
} else {
if ( isset( $_SERVER['REMOTE_ADDR'] ) && ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = 'unkown'
}
}
}
//PHP 7
function get_ip( array $trusted_proxies = [] ) : string {
if ( ! empty( $trusted_proxies ) && isset( $_SERVER['REMOTE_ADDR'] ) && ! in_array( $_SERVER['REMOTE_ADDR'], $trusted_proxies ) ) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?:
$_SERVER['HTTP_CLIENT_IP'] ?:
$_SERVER['HTTP_X_FORWARDED_FOR'] ?:
$_SERVER['HTTP_FORWARDED_FOR'] ?:
$_SERVER['HTTP_FORWARDED'] ?:
'unkown';
return array_pop( array_diff( array_map( 'trim', explode( ',', $ip ) ), $trusted_proxies ) ) ?: 'unknown';
} else {
return $_SERVER['REMOTE_ADDR'] ?: 'unkown';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment