You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

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