How can I get the client's IP address in Zend-framework 2? It'd be $_SERVER['REMOTE_ADDR'] in plain PHP, but maybe is smart Zend function?
Any ideas?
You can use the Zend\Http\PhpEnvironment\RemoteAddress
class to get the client ip address.
$remote = new Zend\Http\PhpEnvironment\RemoteAddress;
echo $remote->getIpAddress();
See http://framework.zend.com/apidoc/2.1/classes/Zend.Http.PhpEnvironment.RemoteAddress.html.
Note:
To enable inspection of the header HTTP_X_FORWARDED_FOR
, turn on setUseProxy()
:
$remote->setUseProxy()->getIpAddress();
The request object(s) in ZF2 has method named getServer
. This method returns an object implementing \Zend\Stdlib\ParametersInterface
. With this particular object you can get anything from the $_SERVER variable.
Here are two examples of how to use the method and object:
<?php
// Getting the entire params object
$servParam = $request->getServer();
$remoteAddr = $servParam->get('REMOTE_ADDR');
// Getting specific variable
$remoteAddr = $request->getServer('REMOTE_ADDR');
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With