Changing request IP address for debugging in CakePHP

in Quick Bites


If you're working on a feature that acts differently based on the request IP address, you would be wanting to test it continuously. For that, you may have to have your application think you're accessing it from a specific/different IP address.

The easiest way would be to just store the IP in a variable and overwrite it once in a while.

// This code will be committed
$client_ip = $this->getRequest()->clientIp();
// Testing code, removed before committing
$client_ip = '1.2.3.4';

The problems swith the above approach are:

  • it requires you to always put your IP into a variable, instead of accessing $this->getRequest()->clientIp() directly;
  • you have to add the overwrite everywhere you need to test the IP and you have to remember to keep it all consistent;
  • it clutters your git diff.

Instead of editing the IP after the fact, you can feed the fake IP into the app, and have it believe that's what you're using. And you can do it in a single place so you don't have to introduce unnecessary edits to the app. And if you do it in config/app_local.php, it won't be picked up by git.

$_SERVER['REMOTE_ADDR'] = '1.2.3.4';