[英]How to escape a shell command to run it from php
嗨,我有一個sed命令,我需要從一個php文件運行,該命令在shell上運行得很好,但是從php提供了apache錯誤,提示問題是分號,我嘗試將所有字符轉義,還嘗試了轉義卷曲剎車,那么apache沒有錯誤,但是命令沒有按預期執行,這是命令
$cmd = "sed -n -i '/ENDSNUMB/{x;d;};1h;1!{x;p;};${x;p;}' ./taggedfiles/$tagfile";
shell_exec($cmd);
用雙引號引起來,PHP嘗試將內聯變量解析為字符串。 您的$
就是問題所在。
嘗試使用單引號並將字符串中的單引號轉義,如下所示:
$cmd = 'sed -n -i \'/ENDSNUMB/{x;d;};1h;1!{x;p;};${x;p;}\' ./taggedfiles/' . $tagfile;
shell_exec($cmd);
不過,在將變量解析為shell代碼時要非常小心。 如果無法正確轉義,則可能容易受到命令注入攻擊。
您可以使用escapeshellcmd
為所有替換值做到這一點......從手冊- 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);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.