Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Get IP Address

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?

like image 809
Aditya P Bhatt Avatar asked Apr 15 '11 10:04

Aditya P Bhatt


3 Answers

CakePHP 1.x:

RequestHandlerComponent::getClientIp();

So to clarify:

public $components = array(
    'RequestHandler'
);

Then in the controller method:

$this->RequestHandler->getClientIp();

CakePHP 2.x & CakepPHP 3.x:

RequestHandler::getClientIp() is deprecated; you can get the client IP from the CakeRequest object:

$this->request->clientIp();
like image 168
rich97 Avatar answered Nov 15 '22 14:11

rich97


CakePHP 3.x usage:

//in controller
$ip = $this->request->clientIp();

CakePHP 2.x usage

//in controller
$this->request->ClientIp();

CakePHP 1.x usage

//in controller
RequestHandlerComponent::getClientIP();
like image 21
Aditya P Bhatt Avatar answered Nov 15 '22 15:11

Aditya P Bhatt


If you need to get the IP address from within a model, $this->request->getClientIp() won't work, throwing:

Error: Call to a member function clientIp() on a non-object

Use Router::getRequest()->clientIp() instead.

So basically, Router::getRequest() can serve as a Model's replacement of the Controller's $this->request

like image 2
mehov Avatar answered Nov 15 '22 14:11

mehov