Member-only story

PHP: Client IP using __invoke and SRP

Luís Nóbrega
3 min readApr 24, 2020

--

Let’s get the unsafe client IP using invokes and complying with the SRP.

Photo by Markus Spiske on Unsplash

SRP means the Single Responsibility Principle and is a recommendation who says that each software module or class should have one and only one reason to change.

Gather together the things that change for the same reasons. Separate those things that change for different reasons.

— Bob Martin

With this principle in mind, I wanted to have a class with only one responsibility, that could give the client IP.

Of course, there are several approaches, and one of them is to use the magic method __invoke.

This way I can have all the logic in one class and don’t need to add an obvious action method.

There are several ways of obtaining the client IP, and even though, appears to be easy an easy task, is not.

First, we should not trust the data sent from the client, because this data can be manipulated, and also the client could be behind a proxy server.

I’ve looked for inspiration in one of the big PHP CMS, WordPress, and found their approach here.

Inspired by that, I would like to guide you through my approach.

Let’s go!

Injecting $_SERVER

--

--

Luís Nóbrega
Luís Nóbrega

Written by Luís Nóbrega

Web Developer at 25friday. Likes to travel, write and being a father.

No responses yet