Skip to content

Instantly share code, notes, and snippets.

@CodeBrauer
Last active January 18, 2022 12:00
Show Gist options
  • Save CodeBrauer/b617e3ef730343ad7accc009b5574514 to your computer and use it in GitHub Desktop.
Save CodeBrauer/b617e3ef730343ad7accc009b5574514 to your computer and use it in GitHub Desktop.
PHP function that anonymizes IP addresses like Google Analytics does (https://support.google.com/analytics/answer/2763052)
<?php
function mask_ip($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$parts = explode('.', $ip);
$parts[count($parts)-1] = '0';
return implode('.', $parts);
} else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$parts = explode(':', $ip);
$parts[count($parts)-1] = '0';
return implode(':', $parts);
} else {
return $ip;
}
}
echo mask_ip('8.8.4.4') . PHP_EOL;
echo mask_ip('54.239.26.128') . PHP_EOL;
echo mask_ip('2001:4860:4860::8888') . PHP_EOL;
echo mask_ip('2001:4860:4860:0:0:0:0:8844') . PHP_EOL;
@CodeBrauer
Copy link
Author

CodeBrauer commented Nov 3, 2017

Script output:

8.8.4.0
54.239.26.0
2001:4860:4860:0
2001:4860:4860:0:0:0:0:0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment