Running shell commands is dangerously simple in PHP

Amit Merchant · August 31, 2022 ·

PHP is one of those languages that are easy to learn and easy to use. But sometimes it surprises you with weird quirks that you would only imagine in your dreams.

One such quirk I came across recently is the ability to run shell commands by wrapping them with backticks.

Essentially, the backticks (``) or execution operators are a way to run shell commands in PHP.

So, let’s say if we want to run whoami shell command that prints the user name associated with the current effective user ID, all we need to do is wrap it with backticks like so and that’s it!

$output = "The current user is " . `whoami`;
echo $output;

// outputs: The current user is amitmerchant

Behind the scenes, PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned. The output can be assigned to a variable as well.

Sure, there’s a degree of convenience attached to this approach but the use of backticks can sometimes proved to be slightly dangerous especially when you’re coming from languages like JavaScript where backticks are used for string interpolation. So, you may mistakenly use backticks for string interpolation but in fact, you’re just running shell commands.

Note: I’m not against the use of backticks at all. If you’re comfortable using them, by all means, feel free to use them.

And because of this confusion, attempts have been made to deprecate this feature since we already have the shell_exec function in PHP that can be used to run shell commands like so.

$output = "The current user is " . shell_exec('whoami');
echo $output;

As you can tell, this is more explicit and safer than using backticks.

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?