看起来您的问题是您没有将代码包装为”来执行.你还需要警惕’代码,特殊字符,转义序列等.
事实上,如果你坚持使用exec(),那么最好这样做(完全避免担心转义等):
$command = base64_encode($command);
exec("php -r 'eval(base64_decode(\"$command\"));'", $output);
您可以使用eval()而不是上面发布的内容.
这里的主要问题(使用eval()和你的exec()代码)从用户输入中获取PHP代码并不安全:
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
建议
由于您想要返回PHP代码的结果,您可以使用AJAX做一些很酷的事情,在这里您可以将PHP代码作为参数传递给脚本(可能是base 64编码):
$code = base64_decode($_GET['code']);
// clean the user input here
eval($code);
使用jQuery的AJAX示例:
// assuming `code` contains the PHP code
var encoded = base64_enc(code);
$.get('execute.php?code=' + encoded, function(data) {
var result = new String(data);
// do something with the result here, such as displaying it
}, dataType='text');
对于JavaScript中的base 64编码,see this.