Magento – get client’s IP

To get customer’s IP, behind a proxy or not, you can use this build in function in magento

1
Mage::app()->getRequest()->getClientIp(true);

refers to lib/Zend/Controller/Request/Http.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
    * Get the client's IP addres
    *
    * @param  boolean $checkProxy
    * @return string
    */
   public function getClientIp($checkProxy = true)
   {
       if ($checkProxy && $this->getServer('HTTP_CLIENT_IP') != null) {
           $ip = $this->getServer('HTTP_CLIENT_IP');
       } else if ($checkProxy && $this->getServer('HTTP_X_FORWARDED_FOR') != null) {
           $ip = $this->getServer('HTTP_X_FORWARDED_FOR');
       } else {
           $ip = $this->getServer('REMOTE_ADDR');
       }
 
       return $ip;
   }

Leave a Reply