Home > OS >  Wordpress - How to get device type and last login location with php
Wordpress - How to get device type and last login location with php

Time:10-04

I wrote this function that allows the user to view the date of the last login (not the current login). Now I would also like to show the location and device with which the login was made. I tried to search but could not find any solution to my problem. Can anyone shed some light on this? I appreciate any help.

// Function that set last login
add_action('wp_login', 'set_last_login', 0, 2);
function set_last_login($login, $user) {
  $user = get_user_by('login',$login);
  $time = current_time( 'timestamp' );
  $last_login = get_user_meta( $user->ID, '_last_login', 'true' );
  if(!$last_login) {
    update_user_meta( $user->ID, '_last_login', $time );
  } 
   else {
    update_user_meta( $user->ID, '_last_login_prev', $last_login );
    update_user_meta( $user->ID, '_last_login', $time );
  }
}

// Function that get last login
function get_last_login($user_id, $prev = null) {
  $last_login = get_user_meta($user_id);
  $time = current_time( 'timestamp' );
  if(isset($last_login['_last_login_prev'][0]) && $prev) {
  $last_login = get_user_meta($user_id, '_last_login_prev', 'true' );
  } 
  else if(isset($last_login['_last_login'][0])) {
    $last_login = get_user_meta($user_id, '_last_login', 'true' );
  } 
  else {
    update_user_meta( $user_id, '_last_login', $time );
    $last_login = $last_login['_last_login'][0];
  } return $last_login;
}

CodePudding user response:

Detect Location:

You might want to consider using the HTML5 Geolocoation API.

Otherwise, the IP may tell you something about the location: How to get Real IP from Visitor?

Other options for location detection includes:

Geolocator-PHP

Google Geocoding API

Maxmind (php)

Detect Device:

https://github.com/serbanghita/Mobile-Detect/

https://www.codexworld.com/mobile-device-detection-in-php/

http://mobiledetect.net/

CodePudding user response:

How to get device type

You can check out the Mobile Detect PHP utility. It uses the User-Agent string and HTTP headers to detect mobile devices.

Here is the Wordpress plugin for it: https://wordpress.org/plugins/tinywp-mobile-detect/

There is a bunch of ports/solutions based on that repo: https://github.com/serbanghita/Mobile-Detect/#modules-plugins-ports

Highly recommend you check out the PHP code examples of Mobile Detect: https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples

require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Basic detection.
$detect->isMobile();
$detect->isTablet();

You can even get browser type information as well:

$detect->is('Chrome')
$detect->is('iOS')
$detect->is('UCBrowser')
$detect->is('Opera')

last login location with php

A fairly simple solution is to use our service, IPinfo. You will get all the location details just by providing the user's IP address. The free tier alone provides up to 50,000 requests per month.

The usage is fairly simple.

Install the IPinfo library with composer first:

php composer.phar require ipinfo/ipinfo

Then you are set. Example code:

require_once __DIR__ . '/vendor/autoload.php';

use ipinfo\ipinfo\IPinfo;

// provide your access token here after you have signed up
// you can get it from your account dashboard
$access_token = 'YOUR_TOKEN'; 
$client = new IPinfo($access_token);
// Pass your IP address here. I am using an arbritary IP address as a placeholder
$ip_address = '8.8.8.8';
$details = $client->getDetails($ip_address);

$details-> all;

This will return an output like this:

[
  "ip"    "8.8.8.8",
  "hostname"    "dns.google",
  "anycast"    true,
  "city"    "Mountain View",
  "region"    "California",
  "country"    "US",
  "loc"    "37.4056,-122.0775",
  "org"    "AS15169 Google LLC",
  "postal"    "94043",
  "timezone"    "America/Los_Angeles",
  "country_name"    "United States",
  "latitude"    "37.4056",
  "longitude"    "-122.0775",
]

You can extract specific information like so:

$details-> city;
// Output: "Mountain View"
$details-> region;
// Ouput: "California"
$details-> country;
// Output: "US"
$details-> loc;
// Output: "37.4056,-122.0775"

CodePudding user response:

You should be able to get the location through javascript through the Location Web API and pass the value through ajax to php and the save it as a metadata.

To use ajax we need to pass it to our script, we will be also passing a nonce:

<?php

wp_enqueue_script( 'my-ajax-script', trailingslashit( get_template_directory_uri() ) . 'assets/js/my-ajax-script.js', array(), wp_get_theme()->version, true );

wp_localize_script( 'my-ajax-script', 'localize', array(
    '_ajax_url' => admin_url( 'admin-ajax.php' ),
    '_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );

Our javascript request call function:

if ( navigator.geolocation ) {
    window.navigator.geolocation.getCurrentPosition( function( position ) {
        $.ajax( {
            type: 'POST',
            url: localize._ajax_url,
            data: {
                _ajax_nonce: localize._ajax_nonce,
                action: '_wpso_73934145',
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
            },
            success: function ( response ) {
                console.log( response.data );
            },
        } );
    } );
};

The php action function:

<?php

add_action( 'wp_ajax__wpso_73934145', function () {

    if ( check_ajax_referer( '_ajax_nonce' ) ) {

        $user_id = get_current_user_id();

        $latitude = $_POST['latitude'];

        $longitude = $_POST['longitude'];

        $meta_key = '_user_position';

        $meta_value = array(
            'latitude' => $latitude,
            'longitude ' => $longitude,
        );

        update_user_meta( $user_id, $meta_key, $meta_value );

        wp_send_json_success( $meta_value );

    } else {

        wp_send_json_error();

    };

    wp_die();

} );

In regards to the device we can retrieve the user agent:

<?php

add_action( 'init', function () {

    if ( is_user_logged_in() ) {

        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        var_dump( $user_agent );

    };

} );
  • Related