Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user ip address in zend framework [closed]

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?

like image 279
lolalola Avatar asked Apr 09 '13 18:04

lolalola


2 Answers

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();
like image 171
radnan Avatar answered Oct 25 '22 22:10

radnan


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');
?>
like image 30
Stoyan Dimov Avatar answered Oct 25 '22 22:10

Stoyan Dimov