Show progress of code executed on form submit I have a form in my site (custom module) where the user chooses some options and depending on those options, some code is executed.

The code basically executes shell commands on a remote server and at the moment, all the drupal_set_message commands are only shown after all commands are executed.

Is there any way that I can show those messages as soon as each part of the code is executed?

function mymodule_connect() {
    $host = '&lt;my ip address&gt;';
    $username = '&lt;my username&gt;';
    $password = '&lt;my password&gt;';

    $connection = ssh2_connect($host, 22);
    ssh2_auth_password($connection, $username, $password);

    return $connection;
}

function mymodule_form_submit(&amp;$form, &amp;$form_state) {

    $delete_load = $form_state['values']['delete_load'];
    $change_load = $form_state['values']['change_load'];
    $load_number = $form_state['values']['check_load'];


    if($change_load == 1) {
        # DELETE
        # perform some command

        # LOAD
        # perform other command

        drupal_set_message('Deleting. Please wait...', 'error');
        drupal_set_message('Changing load. Please wait...', 'warning');
    } elseif ($delete_load == 1 &amp;&amp; $change_load == 0) {
        # DELETE    
        drupal_set_message('Deleting. Please wait...', 'error');

        $command = "&lt;some shell script command to send&gt;";

        $connection = mymodule_connect();

        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);

        ssh2_exec($connection, 'exit');
        unset($connection);

    } else {
        # do nothing
    }

    # OTHER DIFFERENT SET OF COMMANDS TO SEND
    drupal_set_message('Configuring. Please wait...', 'status');

    $commands = array(
        "&lt;some shell script command to send&gt;",
        "&lt;some shell script command to send&gt;",
        "&lt;some shell script command to send&gt;",
    );

    $connection = mymodule_connect();

    foreach ($commands as $command) {
        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);
    };

    ssh2_exec($connection, 'exit');
    unset($connection);

    return t('Success');
}
Surely you need to implement Batch API to achieve what you need, and keep the user notified for what's happening in the background.

Very similar question that will help you more. Read it carefully.

These modules will help you:


Progerss This is an attempt to implement a generic framework for keeping track of any progress 
Background progress takes over the existing Batch API and runs batch jobs in a background process