How can I get the client's IP address in CakePHP? It'd be $_SERVER['REMOTE_ADDR']
in plain PHP.
I thought it's like all $_SERVER
vars and can be accessed using env('VAR_NAME')
, or getClientIP()
in CakePHP, but it doesn't return the same results.
Any ideas?
If you need to get the IP address from within a model,
$this->request->getClientIp()
won't work, throwing:Use
Router::getRequest()->clientIp()
instead.So basically,
Router::getRequest()
can serve as a Model's replacement of the Controller's$this->request
Cakephp 3 have clientIP function in the class ServerRequest:
You can access:
in a controller controller:
in a controller controller:
I leave the function if you use a previous version of the framework or require some special behavior:
For example, this function returns the value ":: 1" when you work in a local environment.
It is a good idea to add it in the bootstrap.php boot file, since you can access it from anywhere:
good luck and happy coding! =D
CakePHP 3.x usage:
CakePHP 2.x usage
CakePHP 1.x usage
In cakephp 3.x
In your controller to get the client ip - $this->request->clientIp();
CakePHP 1.x:
RequestHandlerComponent::getClientIp();
So to clarify:
Then in the controller method:
CakePHP 2.x:
RequestHandler::getClientIp()
is deprecated; you can get the client IP from theCakeRequest
object:You can use
$this->request->clientIp();
to get the current visitor's IP address.For further reference https://book.cakephp.org/3.0/en/controllers/request-response.html#reading-http-headers