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?
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):You could use
eval()instead of what you’re posting above.The main issue here (both with
eval()and yourexec()code) is that taking PHP code from user input simply isn’t safe: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:
Ajax example using jQuery:
For Base64 encoding in JavaScript, see this.