Skip to content
Advertisement

Inline PHP (command line)

I would like to make something like tryruby.org. I take a line from the user (e.g., echo __FILE__) and I want to execute it in PHP and return the output back to the client.

I tried to do exec('php -r ' . $command, $output), but $output always contains the PHP help section.

How can I implement this feature?

Advertisement

Answer

It looks like your problem is that you aren’t wrapping your code to be executed with ' '. You also need to be wary of ' in the code, special characters, escape sequences, etc.

In fact, if you insist on using exec(), it might be better to do this (to completely avoid having to worry about escaping and the such):

$command = base64_encode($command);
exec("php -r 'eval(base64_decode("$command"));'", $output);

You could use eval() instead of what you’re posting above.

The main issue here (both with eval() and your exec() code) is that taking PHP code from user input simply isn’t safe:

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.

Suggestion

Since you want to return the result of the PHP code, you could potentially do something cool with Ajax, where you pass the PHP code to a script (Base64 encoded, perhaps) as a parameter:

$code = base64_decode($_GET['code']);
// Clean the user input here
eval($code);

Ajax example using jQuery:

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

For Base64 encoding in JavaScript, see this.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement