Posted By

GabeLG on 06/11/12


Tagged

php


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

boksiora


Execute a PHP file only if it has changed


 / Published in: PHP
 

Usage:

watch -d -n 1 'php watch.php -f test.php'

Where watch.php is the name of this PHP file where you save this snippet and test.php is the PHP file you are editing. This will allow you to watch the output of the file while you edit it.

Aptana/Eclipse has a terminal window view, that you can use to watch your code executed live with this snippet.

  1. <?php
  2. /**
  3.  * Execute a PHP file given by the -f option only if it has changed
  4.  * @author [email protected]
  5.  * @link http://www.fijiwebdesign.com/
  6.  */
  7.  
  8. // eg: php watch.php -f test.php
  9. // will have $file = test.php
  10. $opts = getopt("f:");
  11. $file = $opts['f'];
  12.  
  13. if (!is_file($file)) {
  14. die('Please specify a file via the -f option.');
  15. }
  16.  
  17. // should we execute file
  18. $exec = false;
  19.  
  20. // our compare for this file changes
  21. $meta_file = sys_get_temp_dir() . '/' . md5($file);
  22. // our file where output is saved
  23. $output_file = $meta_file . '-out';
  24.  
  25. // current hash of file contents
  26. $curr_hash = md5(file_get_contents($file));
  27.  
  28. // old hash of file contents
  29. if (file_exists($meta_file)) {
  30. $old_hash = file_get_contents($meta_file);
  31.  
  32. // if the hashes do not match, a change occurred in content
  33. if ($old_hash != $curr_hash) {
  34. // execute file since it changed
  35. $exec = true;
  36. }
  37.  
  38. } else {
  39. // execute file since first run
  40. $exec = true;
  41. }
  42.  
  43. // save the current file content hash to our meta file
  44. file_put_contents($meta_file, $curr_hash);
  45.  
  46. // our ouput buffer
  47. $output = '';
  48.  
  49. // execute our file if changed
  50. if ($exec) {
  51. require($file);
  52. $output = ob_get_clean();
  53.  
  54. // save output for display later also
  55. file_put_contents($output_file, $output);
  56. } else {
  57. if (file_exists($output_file)) {
  58. $output = file_get_contents($output_file);
  59. }
  60. }
  61.  
  62. // display our output
  63. echo $output;

Report this snippet  

You need to login to post a comment.