Tag: filter-var

  • Stopping WordPress User Registration Spam

    Stopping WordPress User Registration Spam

    I’ve had a rash of user registration spam lately, and even though I’m sure the site is secure, it’s just very annoying. So I’ve whipped up a quick little hook that I’ve thrown in my mu-plugins to give me the ability to add email hostnames to a blocklist and disable user registration from them:

    /**
     * Hook into the user registration process to deny registration to a blocklist of hostnames.
     *
     * @param string   $sanitized_user_login The sanitized username.
     * @param string   $user_email The user's email address.
     * @param WP_Error $errors Contains any errors with the registration process.
     *
     * @return void
     */
    function emrikol_blocklist_email_registration( string $sanitized_user_login, string $user_email, WP_Error $errors ): void {
    	// Validate the email address.
    	if ( filter_var( $user_email, FILTER_VALIDATE_EMAIL ) ) {
    		// Extract the email hostname from the user's email address and normalize it.
    		$email_parts  = explode( '@', $user_email );
    		$email_hostname = strtolower( $email_parts[1] );
    
    		$blocklist = array(
    			'email.imailfree.cc',
    			'mail.imailfree.cc',
    			'mailbox.imailfree.cc',
    		);
    
    		// Check if the email hostname is in the blocklist.
    		if ( in_array( $email_hostname, $blocklist ) ) {
    			$errors->add( 'email_hostname_blocked', __( 'Sorry, registration using this email hostname is not allowed.', 'emrikol' ) );
    		}
    	}
    }
    add_action( 'register_post', 'emrikol_blocklist_email_registration', 10, 3 );
    Code language: PHP (php)

    There’s lots of different ways you could extend this for yourself, like adding a hostname regex, a filter, or an admin screen to allow updates to the blocklist without having to make a code deploy.