William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: calling process to run in the back-end

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:

$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:

 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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: