Andrés Chandía
Andrés Chandía

Reputation: 1049

How to escape a shell command to run it from php

Hi there I have a sed command that I need to run from a php file, the command runs just fine at shell, but from php gives apache errors saying the problem are the semicolon, I tried escaping them all, I also tried escaping the curly brakets, then there is no error at apache but the command don't do as expected, here's the command

$cmd = "sed -n -i '/ENDSNUMB/{x;d;};1h;1!{x;p;};${x;p;}' ./taggedfiles/$tagfile";
shell_exec($cmd);

Upvotes: 0

Views: 1925

Answers (2)

Ivar
Ivar

Reputation: 6858

In double quotes, PHP tries to parse inline variables into the string. Your $ is the problem.

Try using single quotes and escape the ones in your string like this:

$cmd = 'sed -n -i \'/ENDSNUMB/{x;d;};1h;1!{x;p;};${x;p;}\' ./taggedfiles/' . $tagfile;
shell_exec($cmd);

Be very careful with parsing variables into shell code though. Without escaping it properly you might be vulnerable for Command Injection attacks.

Upvotes: 2

Nigel Ren
Nigel Ren

Reputation: 57131

You can use escapeshellcmd to do this for all the replacement values... From the manual - http://php.net/manual/en/function.escapeshellcmd.php

<?php
// We allow arbitrary number of arguments intentionally here.
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);

shell_exec($escaped_command);
?>

Upvotes: 0

Related Questions