Running shell commands is dangerously simple in PHP — Amit Merchant — A blog on PHP, JavaScript, and more

0
12

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 prove 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 this.

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

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

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here