I am developing an online coding competition application. In this I want the code submitted to be compiled and executed. If the submitted code is in Java I am able to compile it using exec
(javac filename).
But how should I run that code such so it will take input from a file and redirect the output to another file? Any other way to check that code for various test cases will also be useful.
exec('java ./$path > ./$dest')
This is what I am using to execute but it is not working.
You have messed with the string interpolation, so you should use:
$path = "path/to/java/file.java";
$dest = "path/to/output.o";
exec("java ./{$path} > ./{$dest}")
But it lacks some basic security considerations.
Unless you want a smart-enough user to execute whatever code he likes on your machine, remember:
And exec is dangerous. Consider a system call in that java file executing rm -rf ~
. I bet there's some java or php alternative for stuff like this, that would execute it in a more or less safe environment.
Also, if I pass $dest = '../../some/evil/path/file.o'
, then the file would be in the directory you don't expect it to (but I guess it's not so critical since you set those paths).