• Blogs (9)
    • đŸ“± 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • PHP: calling process to run in the back-end

    Blogs20122012-09-17


    PHP: calling process to run in the backend

    Sometimes we need PHP to call server-side scripts. e.g., using PHP to call Perl’s cgi or bash script to do some server-side stuff. There are 2 possible issues:

    (1) calling a script without waiting

    Here is my way to implement the without waiting calling:

    <php
    $key = trim($_POST['key']);
    if (!empty($key)) {
     exec("/cgi-bin/search.pl '" . $key ."' >/dev/null 2>&1 &");
     // or:
     // exec("nohup /cgi-bin/search.pl '" . $key ."' >/dev/null 2>&1 &");
    }

    By using ’&’ at the end of the command, Linux will fork a new child process to execute the Perl script (.pl), thus, seperate it from the original php script.

    The benefit is that the php script doesn’t need to wait for processing’s return, no waiting time, just dispatching a task to run back-end. This is very useful in the case of using webpage-form to trigger a ‘backup’ process or ‘searching’ process. User clicks a button, close the page, and just let it do!

    (2) call a script and wait for return result.

    How about calling a process with return value? Here is the way:

    <php
     system("/bin/process.sh >/dev/null 2>&1", $retval);
     if ($retval == 0) echo 'success';
     else echo 'failue';
    ?>

    Notice: here is no ’&’ at the end of the command, and we use ‘system’ command instead of ‘exec’ because it comes with return value, not fork a child-process and let it go.
    After the calling, immediately we judge the return value, here is $retval, to decide next step to go.