output.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <html>
  2. <body>
  3. <?php
  4. $saving = $_REQUEST['saving']; //check whether a saving request is provided
  5. if ($saving == 1) //do if saving request is provided
  6. {
  7. $data = $_POST['data']; //extract the code from the form into a variable
  8. $args = $_POST['args']; //extract the command-line arguments from the form into a variable
  9. $stdin= $_POST['stdin']; //extract the standard input from the form into a variable
  10. $unique = rand(1, 10000); //generate a random number for the current execution session
  11. $file = "prog".$unique.".c"; //declare the file name
  12. $srcpath = "./".$file; //declare the source file path
  13. $executable = "./"."prog".$unique.".bin"; //declare the executable path
  14. $fp = fopen($file, "w") or die("<p>Couldn't open $file for writing!</p>"); //open file for writing
  15. if(!fwrite($fp, $data)) //write the code to file
  16. {
  17. shell_exec("rm -rf $srcpath");
  18. die("<p>Couldn't write values to file!</p>"); //clean up and exit if unable to write
  19. }
  20. fclose($fp); //close and save the file
  21. echo "<p>Saved to $file successfully!</p>"; //notify the user that file has been saved
  22. echo"<p>Compiling the program $file<br>";
  23. $output1 = shell_exec("g++ $srcpath -o $executable 2>&1");
  24. /* try compiling the program with GCC and collect errors and warnings */
  25. if($output1!=NULL)
  26. {
  27. echo "Error list:<br><pre>$output1</pre>"; //display the errors and warnings if present
  28. }
  29. echo "</p>";
  30. if(file_exists($executable)) //check if executable exists
  31. {
  32. echo "<p>Running the program:<br>";
  33. $output2 = shell_exec("echo $stdin | $executable $args 2>&1");
  34. /* execute the file providing the necessary inputs and collect the output */
  35. echo "<pre>$output2</pre>";
  36. echo "<br></p>";
  37. }
  38. shell_exec("rm -rf $srcpath $executable"); //clean up the session files
  39. }
  40. else //do if saving request is not provided
  41. {
  42. echo "<p>Enter your code in the left frame and hit run to display the output.</p>";
  43. /* tell the user to fill up the form on the left frame */
  44. }
  45. ?>
  46. </body>
  47. </html>