how to get ip address in codeigniter?

江枫思渺然 提交于 2020-01-09 09:20:09

问题


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.


回答1:


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;



回答2:


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




回答3:


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




回答4:


Controller

$data['ip'] = $this->input->ip_address();

view

<?= $ip ;?>


来源:https://stackoverflow.com/questions/24266212/how-to-get-ip-address-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!