"User Import" Form: How to Avoid PHP Timeouts

Hi guys,

I’ve created a form that imports users to “teams” on my site. For my use-case, I could be importing 2,000+ users at a time. I’ve got the form working, but only if I keep the user count under ~400 per submission.

How could I maybe leverage AJAX to do the user creation/importing and avoid PHPs timeout? I’m on WPEngine and they enforce a strict 60 second script time limit.

Here’s my code:

add_action( 'gform_confirmation_4', 'register_new_members', 10, 4 );
function register_new_members($confirmation, $form, $entry, $ajax){
    if( rgar( $entry, '10' ) == "administrator" && rgar( $entry, '12' ) == 65765){
        $team = wc_memberships_for_teams_get_team( rgar( $entry, '9' ) );
    } else {
        $team = wc_memberships_for_teams_get_team( rgar( $entry, '11' ) );
    }

    if( rgar( $entry, '7' ) == "Import via .csv" ){
        $csv_members = unserialize(rgar( $entry, '2' ));
    } else {
        $csv_members = unserialize(rgar( $entry, '8' ));
    }

    $confirmation_title = "<h2 class='center green'>Your import is complete!</h2>";
    $confirmation_list = "<ol>";

    $row_count = 0;

    foreach ($csv_members as $csv_member){
        $email = $csv_member['Email'];
        $name = $csv_member['Name'];
        $password = (empty($csv_member['Password'])) ? wp_generate_password() : $csv_member['Password'];
        $role = strtolower((!$csv_member['Role']) ? 'member' : $csv_member['Role']);

        if(get_user_by('email', $email)){
            $user = get_user_by('email', $email);
            //wp_update_user( array( 'ID' => $user->ID, 'display_name' => $name ) );
            $team->add_member($user->ID, $role);
            $confirmation_list .= "<li>$email added to team.</li>";
        } else{
            $user_id = wp_create_user( $email, $password, $email );
            wp_update_user( array( 'ID' => $user_id, 'display_name' => $name ) );
            $team->add_member($user_id, $role);
            $confirmation_list .= "<li>$email account created and added to team.</li>";
        }

        $row_count++;
    }

    $confirmation_list .= "</ol>";

    $confirmation_title .= "<p class='center green'>$row_count new users were added to ".$team->get_name().". You have ".$team->get_remaining_seat_count()." seats remaining.</p>";

    $confirmation_button = '<p class="center"><a href="/team-member-imports/?team_id='.$team->get_id().'" class="button greenbg">Import More Users</a></p>';

    $confirmation = $confirmation_title.$confirmation_list.$confirmation_button;

    return $confirmation;
}