how to get ip address in codeigniter?

user3680002 picture user3680002 · Jun 17, 2014 · Viewed 93.7k times · Source

I am doing this following code for login attempt & i want get IP address of my local machine..

if ( !$this->session->userdata('login_attempts') )
{
   $this->session->set_userdata('login_attempts', 0);
}
$attempts = ($this->session->userdata('login_attempts') + 1);
$this->session->set_userdata('login_attempts', $attempts);
// Check if the session.
if ( $this->session->userdata('login_attempts') > 4 )
{
    echo 'hi....login attempt is over';
}
// Failed. So, update the session    

echo $ip = $_SERVER['REMOTE_ADDR'];
// $ip_address = $this->input->ip_address1();
// return $ip_address;
echo $this->input->ip_address();
if ( ! $this->input->valid_ip($ip))
{
    echo 'Not Valid';
}
else
{
    echo 'Valid';
}
$this->db->update('loginattempts',array( 'login_attempts' =>$this->session->userdata('login_attempts') , 'lastLogin' =>date('Y-m-d H:i:s'),'ip'=>$ip = $_SERVER['REMOTE_ADDR'] ),array('login_id' =>1) );
echo ('hi....login attempt is'.$this->session->userdata('login_attempts'));

}

but it show incorrect ip address of my local machine.

Answer

Dan picture Dan · Jun 17, 2014

Use $this->input->ip_address();

Codeigniter Input User Guide (ip_address)

Also, don't echo an equation. echo on another line instead:

$ip = $this->input->ip_address();
echo $ip;