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.
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.
👋 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!