grpaiva
grpaiva

Reputation: 582

Codeigniter's Session Library: How to get the correct IP Address when using Proxy

I have an application that uses Codeigniter 3x and Cloudflare for adding an extra security layer.

When I use $_SERVER['REMOTE_ADDR'] my application returns Cloudflare's IP and not my user's IP, so I always need to use $_SERVER['HTTP_CF_CONNECTING_IP'] instead.

So far, ok. When I need my user's IP in any controller I reach out to $_SERVER['HTTP_CF_CONNECTING_IP']. The problem is that my Session Library doesn't do that. And my ci_sessions table is filled with Cloudflare's IPs.

So my question may be a little broad, but I needed some ideas on how to fix that without messing with CI's core files? I've noticed that there's a file on system/libraries/session/drivers/Session_database_driver.php that is using the remote address. How can I extend it?

Cheers!

Upvotes: 2

Views: 1503

Answers (1)

grpaiva
grpaiva

Reputation: 582

So, as @Narf commented, ci_sessions ip_address only matters if you use sess_match_ip (that's a setting in config.php). And, in his own words:

that's not sustainable outside of intranet environments, because public IP addresses can change often

So his recommendation is to leave ci_sessions table with Cloudfare's addresses. I thought it would be good to leave this here for future reference.

But if you really need to create custom drivers, @DFriend's recommendation works like a charm. You can find more information about this on CI's user guide, in this section.

And if you want to get your user's IP for another purpose, just use $_SERVER['HTTP_CF_CONNECTING_IP'] or even $this->server('HTTP_CF_CONNECTING_IP'). It works for me.

I really want to thank you guys for helping me figure this out.

Cheers!

Upvotes: 1

Related Questions