Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Running shell commands is dangerously simple in PHP

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 (including 8.1, 8.2, 8.3, and 8.4), 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-digest 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?