Last active
September 5, 2022 15:13
-
-
Save vasartam/cb99e58b6ed232794b50b507ff02b2e6 to your computer and use it in GitHub Desktop.
PHP - Get remote IP address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Get remote IP address. | |
| * | |
| * @return string|null | |
| * | |
| * @link https://stackoverflow.com/a/41769505/12320578 | |
| */ | |
| function getIp(): ?string { | |
| $ip_headers_keys = [ | |
| 'HTTP_CLIENT_IP', | |
| 'HTTP_X_FORWARDED_FOR', | |
| 'HTTP_X_FORWARDED', | |
| 'HTTP_X_CLUSTER_CLIENT_IP', | |
| 'HTTP_FORWARDED_FOR', | |
| 'HTTP_FORWARDED', | |
| 'REMOTE_ADDR', | |
| ]; | |
| foreach ( $ip_headers_keys as $ip_header_key ) { | |
| if ( array_key_exists( $ip_header_key, $_SERVER ) !== true ) { | |
| continue; | |
| } | |
| foreach ( explode( ',', $_SERVER[ $ip_header_key ] ) as $ip ) { | |
| $ip = trim( $ip ); | |
| if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) === false ) { | |
| continue; | |
| } | |
| return $ip; | |
| } | |
| } | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment