Halloween Sale 15% off Ends in See the plans
PHP

Reject Login Attempts That Don't Come From Your Login Form

Refuses login form submissions that are not sent from a page on your own site, which stops many brute-force bots that post straight to wp-login.php.

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

Code

add_action( 'login_init', function () {
    if ( 'POST' !== ( isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : '' ) || empty( $_POST['log'] ) ) {
        return;
    }

    $own    = wp_parse_url( site_url(), PHP_URL_HOST );
    $origin = isset( $_SERVER['HTTP_ORIGIN'] ) ? wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) ), PHP_URL_HOST ) : '';
    $ref    = isset( $_SERVER['HTTP_REFERER'] ) ? wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ), PHP_URL_HOST ) : '';
    $home   = wp_parse_url( home_url(), PHP_URL_HOST );

    if ( in_array( $origin ? $origin : $ref, array( $own, $home ), true ) ) {
        return;
    }

    status_header( 403 );
    wp_die( esc_html__( 'Please log in using the login form on this site.' ), 403 );
}, 1 );

Notes

Browsers send the needed Origin or Referer header automatically; disable the snippet if a mobile app or external form logs users in through wp-login.php.

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.