20221127

How to detect real client ip in swoole laravel octane without nginx but behind a reverse proxy

 

When using Laravel Octane without nginx and you're behind a load balancer like Google Cloud Platform's or Amazon AWS or other reverse proxy that sets X-FORWARDED-FOR header, you must check this header to get the real client IP.

I've tried setting TrustedProxies etc. with no succes. And Laravel Octane didn't get it right when you call request()->ip()

Finally I've found the solution getting the server parameter HTTP_X_FORWARDED_FOR from the request and getting the first IP from a comma separated list. 


Check in your particular case if maybe the client IP is set in other header like HTTP_REAL_IP or similar using dd(request()->server) to get all the parameters bag.

You can use this sample class (adjust your namespace):

<?php

namespace YourOrg\Helpers;

class Ip {
    public static function get () {
        $XFFip=request()->server->get('HTTP_X_FORWARDED_FOR');
        if ($XFFip) {
            $ips = explode(',', $XFFip);
            $ips = array_map('trim', $ips);
            $ip = $ips[0];        
        } else {
            $ip=request()->ip();
        }
        return $ip;
    }
}


Then anywhere in your code you can use:

use YourOrg\Helpers\Ip;

...

echo Ip::get();


Have fun