Anonymizing an IP address with Symfony

Published on 2022-10-23 • Modified on 2022-10-23

This snippet shows how to anonymize an IP address with Symfony. We can use the IpUtils class which handles both V4 and V6 addresses. You can find your real IP on this page.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\Request;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet226Trait
{
    public function snippet226(Request $request): void
    {
        echo 'You anonymized IP is: '.IpUtils::anonymize($request->getClientIp() ?? '127.0.0.1');

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!