user3680002
user3680002

Reputation: 301

how to get ip address in codeigniter?

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.

Upvotes: 29

Views: 125652

Answers (4)

Dan
Dan

Reputation: 9468

Use $this->input->ip_address()

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

Or in CI4: $this->request->getIPAddress()

$ip = $this->request->getIPAddress();

Upvotes: 85

Sumari Marco
Sumari Marco

Reputation: 9

You can use on an external service if you trust that it will have 100% uptime.

$ip = file_get_contents('https://api.ipify.org');

Upvotes: 0

BALAJI R
BALAJI R

Reputation: 73

use anyone from below .. same like $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_FOR']

$_SERVER['HTTP_CF_CONNECTING_IP']

We should use codeigniter function for security, we should use $this->input->ip_address(); , This will give client ip

If you want to access server variable use like this

$this->input->server(array('HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR')));

For reference please have a look https://www.codeigniter.com/user_guide/libraries/input.html

Upvotes: 1

Ryan
Ryan

Reputation: 14649

To get the remote IP address, in PHP, you could use $_SERVER['REMOTE_ADDR'], CodeIgniter is doing the same thing behind the scenes.

Upvotes: 4

Related Questions