Skip to content

Instantly share code, notes, and snippets.

@Manapyzz
Last active November 5, 2021 16:02
Show Gist options
  • Save Manapyzz/6da46335d16d710a5b5a85fe45767485 to your computer and use it in GitHub Desktop.
Save Manapyzz/6da46335d16d710a5b5a85fe45767485 to your computer and use it in GitHub Desktop.
FakeIpSimulation

Fake Ip Simulation

Ce gist n'a pour but que de simuler différentes fausses adresses ip pour le bonus sur le projet tutube v2: https://gist.github.com/Manapyzz/5a9258c7547028a520c9a48f6cd3a05c

  1. Créer un dossier "EventSubscriber" dans votre dossier "src".

  2. Créer ensuite à l'intérieur de ce dossier un fichier nommé "RandomIpSubscriber.php"

  3. Copier/coller le code ci-dessous dans ce fichier.

  4. Vous n'avez le droit de modifier uniquement que les constantes "RANDOM_IP" et "IP_TO_USE":

    • Si "RANDOM_IP" est à "true", une ip aléatoire sera générée à chaque requête.
    • Si "RANDOM_IP" est à "false", la valeur contenu dans "IP_TO_USE" sera utilisé constamment à chaque requête.
  5. Une fois le bonus fait je vous conseille de supprimer ce fichier de votre projet.

<?php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RandomIpSubscriber implements EventSubscriberInterface
{
    const RANDOM_IP = true;
    const IP_TO_USE = '123.456.789';

    public function onKernelController(ControllerEvent $event)
    {
        $randomIp = self::IP_TO_USE;

        if (self::RANDOM_IP)
        {
            $randomIp = mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255);
        }

        if (empty($randomIp) && !filter_var($randomIp, FILTER_VALIDATE_IP))
        {
            throw new \Exception('Fake Ip has an incorrect format');
        }

        $event->getRequest()->server->set('REMOTE_ADDR', $randomIp);
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::CONTROLLER => 'onKernelController',
        ];
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment