Linux Programming Web Technology

Properly execute shell commands and return errors in PHP

Sometimes you want to run a command on your server through PHP. There are couple of ways to do it, system()exec()shell_exec(), passthru(). All of them pretty much works alright with some slight differences. I would like to share my method which I think is more “programmatic”.

This is an example, it execute a backup of the whole mysql database. (1234 is the password)

Linux/Unix conventions

You may ask how do I know what’s the return code from the shell command means. In fact, there is a set of convention among most Unix commands. Please reference to this Stackoverflow post. Although you may not sure what convention the command is using, you can be safe to assume code 0 means success.

Exception propagation

Since the error happen when you invoke the command will not be thrown in PHP environment, You have to throw it manually.

Full Example

The code in in Laravel, but the idea can be applied everywhere.


Share your thoughts