Home > OS >  Is there a way to make my site automatically check if a user is still logged in every x minutes?
Is there a way to make my site automatically check if a user is still logged in every x minutes?

Time:09-27

I have a site where i sell streaming videos, and i'm currently using a plugin that prevents account sharing by allowing only one device logged at a time. The problem is, the user can start watching the stream and then share his account, the second person will access the stream and both of them will watch because User 1 didn't refresh the page (which will log him out). How can i make the site automatically check every x minutes if user 1 is still logged in and if he isn't, refresh the page?

CodePudding user response:

One way to do this would be to have the page call out to you on an interval using Javascript asynchronously. (e.g. ajax)

Depending on how the streaming works you could even terminate further streaming if you do not get the interval call after a set amount of time.

CodePudding user response:

First of all, this is a great question !

The problem here is to periodically check if a user is logged in, tho as you understand PHP doesn't refresh on its own.

Like @Chris Haas pointed out, the following article "Check if user is logged in using JQuery" is pretty close to the behavior you're looking for, tho we need to set up, and understand a few thing.

We can pass variable from PHP to Javascript through the wp_localize_script() WordPress function...

...Tho, if we just localize the is_user_logged_in() as a variable, then the function would only be trigger once, meaning when the script is actually enqueued.

The answer to our problem is triggering back a PHP function from our Javascript through Ajax.

From our function.php: Since Ajax is already built into the core WordPress administration screens, passing it to the front end is fairly easy.

<?php

//enqueue jquery
wp_enqueue_script( 'jquery-min', 'https://code.jquery.com/jquery-3.6.1.min.js', array(), '3.6.1', true );

//add jquery integrity key
add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) {

    if ( 'jquery-min' === $handle ) {

        $tag = str_replace(
            "></script>",
            " integrity='sha256-o88AwQnZB VDvE9tvIXrMQaPlFFSUTR nldQm1LuPXQ=' crossorigin='anonymous'></script>",
            $tag
        );

    };

    return $tag;

}, 10, 3 );

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

//pass ajax and a nonce to my-script
wp_localize_script( 'my-script', 'localize', array(
    '_ajax_url' => admin_url( 'admin-ajax.php' ),
    '_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );

Keep in mind that Ajax is dependend on JQuery, that's why my-script.js is depended on JQuery.

From our my-script.js: Our Ajax request is wrapped in a setInterval method firing every seconds. If the answer sent from the matching PHP function is false we force reload the whole page through location.reload().

setInterval( function ( event ) {
    $.ajax( {
        type: 'POST',
        url: localize._ajax_url,
        context: this,
        data: {
            _ajax_nonce: localize._ajax_nonce,
            action: '_wpso_73857697_is_user_logged_in',
        },
        success: function ( response ) {
            let is_user_logged_in = response.data;
            switch ( is_user_logged_in ) {
                case true:
                    break;
                case false:
                    location.reload();
                    break;
                default:
                    break;
            };
        },
    } );
}, 1000 );

From our function.php: The matching PHP function will check if the user is logged-in upon receiving the request sent by our self triggering Ajax function. It will send back a response containing the user status (true/false).

<?php

//for NON-logged-in users
add_action( 'wp_ajax_nopriv__wpso_73857697_is_user_logged_in', function () {

    $is_user_logged_in = is_user_logged_in();

    wp_send_json_success( $is_user_logged_in );

    wp_die();

} );

//for logged-in users
add_action( 'wp_ajax__wpso_73857697_is_user_logged_in', function () {

    if ( check_ajax_referer( '_ajax_nonce' ) ) {

        $is_user_logged_in = is_user_logged_in();

        wp_send_json_success( $is_user_logged_in );

    } else {
                    
        wp_send_json_error();

    };

    wp_die();

} );

CodePudding user response:

First of all, you need to enqueue your js file in functions.php.

add_action('wp_enqueue_scripts', 'load_files');

    function load_files()
    {
        wp_enqueue_script('customjs', get_template_directory_uri().'/custom.js', array('jquery'), '1.0.0', true);
        wp_localize_script('customjs', 'myVAr', array('ajax_url' => admin_url('admin-ajax.php')));
    }

Then add jquery code to your js file:

This function will run every second. You can modify it as per your requirements.

    (function ($) {
  setInterval(function () {
    $.ajax({
      url: myVAr.ajax_url,
      type: "POST",
      data: {
        action: "is_user_logged_in",
      },
      success: function (response) {
        if (response == "no") {
          location.reload(true);     //reload your page if user is looged in
        }
      },
    });
  }, 1000);     //function will run every seconds
})(jQuery);

In our functions.php file:

add_action('wp_ajax_is_user_logged_in', 'check_user_is_logged_in');
add_action('wp_ajax_nopriv_is_user_logged_in', 'check_user_is_logged_in');

function check_user_is_logged_in()
{
    echo is_user_logged_in() ? 'yes' : 'no';
    exit;
}

As we get a response from ajax, if the user is not logged in, it automatically reloads the page every second.

  • Related