Halloween Sale 15% off Ends in See the plans
PHP

Ask for the Password Again Before Sensitive Admin Screens

Requires administrators to log in again before opening plugin, theme, user and update screens when their login is older than 30 minutes, so a hijacked session cannot quietly install code or add users.

Don’t have WPIDE yet? Install it on your site

Code

// Maximum age of the login, and the admin screens that need a fresh one.
$wpide_reauth_minutes = 30;
$wpide_reauth_screens = array( 'plugins.php', 'plugin-install.php', 'plugin-editor.php', 'theme-install.php', 'theme-editor.php', 'user-new.php', 'update-core.php', 'users.php' );

foreach ( $wpide_reauth_screens as $wpide_screen ) {
    add_action( 'load-' . $wpide_screen, function () use ( $wpide_reauth_minutes ) {
        if ( wp_doing_ajax() || 'POST' === ( isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET' ) ) {
            return;
        }

        $token   = wp_get_session_token();
        $session = $token ? WP_Session_Tokens::get_instance( get_current_user_id() )->get( $token ) : null;

        if ( ! empty( $session['login'] ) && ( time() - (int) $session['login'] ) <= $wpide_reauth_minutes * MINUTE_IN_SECONDS ) {
            return;
        }

        $here = set_url_scheme( 'http://' . ( isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '' ) );
        wp_safe_redirect( wp_login_url( $here, true ) );
        exit;
    } );
}

Notes

Adjust $wpide_reauth_minutes and the list of screens; after logging in again the user lands back on the screen they asked for.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.