• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • PHP call bash - Without waiting for a return

    Blogs20112011-10-28


    PHP call bash - Without waiting for a return

    Recently I did a web-based server-side process:

    There is 4 buttons in a form, to sequently process a complex task:

    <form>
    <input name="button1" type="button" value="step 1: click to run long-time server-side processing." />
    <input name="button2" type="button" value="step 2: click to batch process data with Database"  />
    <input name="button3" type="button" value="step 3: Cancel the process while running."  />
    <input name="button4" type="button" value="step 4: send a email to congradulate sucessfully process."  />
    </form>

    As it lists, each button has its function:

    1. step 1: when click, a server-side bash script is triggered, to execute long-time upload task, probably more than 1 hour to complete.
    2. step 2: when click, a server-side bash script is triggered, the above uploaded data is processed and inserted into Database.
    3. step 3: when click, the above processing is cancelled.
    4. step 4: when click, send email to celebrate.

    This process involves commands PHP call Linux. such as exec, system, shell_exec, etc. The following is my version:

    ...
    if(isset($_GET['step_1'])) {
     // exec("nohup linux_pth/getCSV.bash >/dev/null 2>&1 &");
     $files = preg_replace("/,/", " ", $_GET['files']);
     exec("linux_pth/run.bash $files >/dev/null 2>&1");
    }
    elseif(isset($_GET['step_2'])) {
     // sync: need result immediately.
     system("linux_pth/process.bash >/dev/null 2>&1", $retval);
     if ($retval == 0) echo $du->errors['4'];
     else echo $error;
    }
    elseif(isset($_GET['step_3'])) {
     // need return variable, result immediately.
     system("kill -9 `ps -ef|grep getCSV|grep -v grep|grep -v vi|awk '{print $2}'`", $retval);
     echo $retval;
    }
    elseif(isset($_GET['step_4'])) {
     send_email($success_message);
    }

    PHP is not suitable for server-side processing, however, for some special case(such as web-based process), it has to do so.