Tag Archives: Shell Scripting

Shell scripting in php to balance your load

19 Apr

It was an issue while I was working with an API module in Magento. I really like the environment and the PHP ticks they used in their development especially I become a great fan of Factory Pattern now.

I had an API call to complete the checkout from a remote server using Magento API and the checkout process executes another 10 to 12 API calls in another server to complete the total process.So see the scenario here.

API CALL Diagram

But, above system will not complete anymore because it will take time more than PHP Maximum execution time.

Then, I have decided to open a new process in Linux with shell script and assign the next API calls there. Checkout API function return after triggering that new process for the further task. The new process execute on its ways and do necessary update in database and then die by itself.

We can do that with a simple Shell call from PHP. Like:

 bash shellscript.sh  Arg1 Arg2


It’s a simple command to run a shell script from command line with command line arguments. But main problem I faced is… to make PHP Asynchronous.
We’ve lots of functions to execute command line instruction like bellow:
exec(), shell_exec(), system(), “

None of these functions will server this problem. All these functions wait until capture any response. But we have to open a new process and have to return leaving on its way.

So I have used the following example. Here we have opened a new process and close it as well:

Proc_Close(Proc_Open ("bash c2m.sh 4 1_2_3_4_5 &", Array (), $foo));


I have added an ampersand(&) that means I don’t care it’s return value.

Rest of the task is pretty simple. In Shell script we capture the command like argument with $0, $1, $2 … etc and we can execute an PHP script in command like bellow

#!/usr/bin/bash

`php myscript.php $1` 


This command run myscript.php and send a command line arguments. All command line argument saved in a PHP variable called $argv

Always use a back quote(`) to execute a php file in shell script if you want to store the output in a variable.
See the following example:

#!/usr/bin/bash

result=`php myscript.php $item_id`

echo "$result"


This is how you can pass your load in Linux to execute command line to get relief from time expire issue. 🙂

Download Example source code from here

Advertisements