bal*_*oke 4 php shell terminal interpreter command-line-interface
我想做一些像tryruby.org的东西.我从用户(例如echo __FILE__
)获取一行,我想在PHP中执行它并将输出返回给客户端.
我试过exec('php -r ' . $command, $output)
但$output
总是包含php帮助部分.
任何人都可以帮助我或提供如何实现此功能的建议.
多谢.
And*_*ren 12
为了让php -r
你必须在'
你的代码之间放置你想要执行的代码..'
例:
php -r ' $var = 34; print_r($var); '
Run Code Online (Sandbox Code Playgroud)
看起来您的问题是您没有包装要执行的代码' '
.您还需要警惕'
代码,特殊字符,转义序列等.
事实上,如果你坚持使用exec()
,那么最好这样做(完全避免担心转义等):
$command = base64_encode($command);
exec("php -r 'eval(base64_decode(\"$command\"));'", $output);
Run Code Online (Sandbox Code Playgroud)
您可以使用eval()
而不是上面发布的内容.
这里的主要问题(包括eval()
和你的exec()
代码)是从用户输入中获取PHP代码是不安全的:
eval()语言构造非常危险,因为它允许执行任意PHP代码.因此不鼓励使用它.如果您已仔细验证除了使用此构造之外没有其他选项,请特别注意不要将任何用户提供的数据传递到其中,而不事先正确验证它.
建议
由于您想要返回PHP代码的结果,您可以使用AJAX做一些很酷的事情,在这里您可以将PHP代码作为参数传递给脚本(可能是base 64编码):
$code = base64_decode($_GET['code']);
// clean the user input here
eval($code);
Run Code Online (Sandbox Code Playgroud)
使用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');
Run Code Online (Sandbox Code Playgroud)
对于JavaScript中的base 64编码,请参阅此内容.