Quickly Run Any PHP Code Through A Form

15th October 2008 - 3 minutes read time

NOTE: This bit of code is potentially very dangerous and should NOT be uploaded to your web host. I only use this function on my localhost to quickly check that a snippet of code works.

If you want to quickly run some PHP code, and don't want to have to go through creating a file just to see the outcome of a simple calculation is then this snippet might be of some use to you.

It works by taking the contents of the textarea and creating a file with the filename of 'tempcodefile.php', which contains that code. The created file is then included in order to run the code, the output of which is displayed at the top of the screen.

  1. <?php
  2. error_reporting(E_ALL);
  3. ini_set('display_errors', 1);
  4. ?>
  5. <html>
  6. <head>
  7. <title>PHP Tester</title>
  8. </head>
  9. <body>
  10. <?php
  11. if (isset($_POST['code'])) {
  12. $code = $_POST['code'];
  13. $file = fopen('tempcodefile.php', 'w');
  14. fwrite($file, $code);
  15. require_once('tempcodefile.php');
  16. } else {
  17. $code = '';
  18. }
  19. ?>
  20. <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  21. <div style="text-align:center">
  22. <textarea rows="30" cols="150" name="code"><?php echo $code; ?>;</textarea>
  23. <br>
  24. <input type="submit" value="Run" />
  25. </div>
  26. </form>
  27. </body>
  28. </html>

To run this code enter some PHP code (including the PHP brackets) into the text box and click on the run button.

The first time the form is run a file will be created containing the code added to the textarea. The code file will be included and run and any output printed out to the top of the screen. Error reporting is turned on so errors are displayed at the start of the script so if you enter something that doesn't work it will tell you about it.

This script is useful if you just want to run something quickly, but beware that if you upload this to your web server you are at risk of someone running some code that will delete all the files on your site.

Add new comment

The content of this field is kept private and will not be shown publicly.