Last active
          January 18, 2022 12:00 
        
      - 
      
- 
        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)
  
        
  
    
      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 | |
| 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; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Script output: