php_cli_server.inc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. define ("PHP_CLI_SERVER_HOSTNAME", "localhost");
  3. define ("PHP_CLI_SERVER_PORT", 8964);
  4. define ("PHP_CLI_SERVER_ADDRESS", PHP_CLI_SERVER_HOSTNAME.":".PHP_CLI_SERVER_PORT);
  5. function php_cli_server_start($ini = "") {
  6. $php_executable = getenv('TEST_PHP_EXECUTABLE');
  7. $doc_root = __DIR__;
  8. $descriptorspec = array(
  9. 0 => STDIN,
  10. 1 => STDOUT,
  11. 2 => STDERR,
  12. );
  13. if (substr(PHP_OS, 0, 3) == 'WIN') {
  14. $cmd = "{$php_executable} -t {$doc_root} $ini -S " . PHP_CLI_SERVER_ADDRESS;
  15. $handle = proc_open(addslashes($cmd), $descriptorspec, $pipes, $doc_root, NULL, array("bypass_shell" => true, "suppress_errors" => true));
  16. } else {
  17. $cmd = "exec {$php_executable} -t {$doc_root} $ini -S " . PHP_CLI_SERVER_ADDRESS . " 2>/dev/null";
  18. $handle = proc_open($cmd, $descriptorspec, $pipes, $doc_root);
  19. }
  20. // note: even when server prints 'Listening on localhost:8964...Press Ctrl-C to quit.'
  21. // it might not be listening yet...need to wait until fsockopen() call returns
  22. $i = 0;
  23. while (($i++ < 30) && !($fp = @fsockopen(PHP_CLI_SERVER_HOSTNAME, PHP_CLI_SERVER_PORT))) {
  24. usleep(10000);
  25. }
  26. if ($fp) {
  27. fclose($fp);
  28. }
  29. register_shutdown_function(
  30. function($handle) {
  31. proc_terminate($handle);
  32. },
  33. $handle
  34. );
  35. // don't bother sleeping, server is already up
  36. // server can take a variable amount of time to be up, so just sleeping a guessed amount of time
  37. // does not work. this is why tests sometimes pass and sometimes fail. to get a reliable pass
  38. // sleeping doesn't work.
  39. }
  40. ?>