简体   繁体   中英

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.

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;

Controller

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

view

<?= $ip ;?>

要获取远程 IP 地址,在 PHP 中,您可以使用$_SERVER['REMOTE_ADDR'] ,CodeIgniter 在幕后做同样的事情。

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

this's simple example code when implementation into mysql insert login log user;

               $ip=file_get_contents('https://api.ipify.org');
                
                  $sql = array(
                      'email_user' => $email,
                      'full_name'  => $full_name,
                      'last_login' => $date,
                      'ipaddress'  => $ip
                      );
                $this->db->insert('$table', $sql);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM