简体   繁体   中英

PHP - Last “date” logged on from this “ipaddress”?

I wanna know if php can remotely store when the user is logged in such as date and ipaddress, maybe use "COOKIES" or a database, I don't know and I'm not sure. Btw, my question means that if last time I logged on was "4/5/2014 from 108.25.1.123"

it would echo

  • Last Login: 4/5/2014 from 108.25.1.123

ignore the database and cookies if im wrong.

You can have a foot.php file in all of your files in the website. That foot.php will have a code something like this:

<?php
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $last_login = date("Y-m-d H:i:s");

    $connection = mysql_connect($server, $username, $password);
    mysql_select_db($db, $connection);
    $query = sprintf('UPDATE table_users SET ip_address=%s, last_login=%s WHERE user_id=%s', $ip_address, $last_login, $_SESSION['user_id']);
?>

This will ensure that whenever a user visits a page in your website, the database will be updated automatically. Hope this helped. :)

Edit: PDO version:

<?php
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $last_login = date("Y-m-d H:i:s");
    $connection = new PDO('mysql:host=localhost;dbname=testdb', $username, $password);
    $query = sprintf('UPDATE table_users SET ip_address=%s, last_login=%s WHERE user_id=%s', $ip_address, $last_login, $_SESSION['user_id']);
    $count = $connection->exec($query);
    printf('Updated $count rows.');
?>

database method after the user successfully logs in you redirect the user I guess, for example

login.hp

if(){
 //validations
 }
 else{
   update_last_sign_in();//call function which updates the last login
  //success redirect the user
  }

you could have this function on some other file or the same page if you want.

 function update_last_sign_in()
 {
 $username = $_SESSION['logged_in_user'];
 $ip = $_SERVER['REMOTE_ADDR'];
 $date =   date('Y-m-d H:i:s');

 $database = new mysqli('localhost', 'user', 'pass', 'database_name');
 $stmt = $database->prepare('UPDATE last_login set username = ?, user_ip = ?, login_date = ?');
 $stmt->bind_param('sss', $username, $ip, $date);
 $stmt->execute();
 }

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