简体   繁体   中英

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);

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.

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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM