Question: 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?

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

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

```

You *could* use [`eval()`](http://php.net/manual/en/function.eval.php) 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](https://en.wikipedia.org/wiki/Base64) encoded, perhaps) as a parameter:

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

```

Ajax example using jQuery:

```js
// 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](https://stackoverflow.com/a/246813/1166205).
<http://tryruby.org> seems have an interactive Ruby shell. That seems to be a good starting point.

Here are two projects that provide such a shell for PHP: [php\_repl](https://github.com/ieure/php_repl) and [phpsh](http://www.phpsh.org/).

The other part is the web interface for the interactive shell. For that part, I suggest you have a look at [repl.it](http://repl.it/), which provides this service for many languages (but sadly not PHP). [Here's a link](https://github.com/replit/repl.it) to it's source code.

With this combination, you should be able to complete cour project.