php_cli_server.inc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. if (substr(PHP_OS, 0, 3) == 'WIN') {
  9. $descriptorspec = array(
  10. 0 => STDIN,
  11. 1 => STDOUT,
  12. 2 => array("pipe", "w"),
  13. );
  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. $descriptorspec = array(
  18. 0 => STDIN,
  19. 1 => STDOUT,
  20. 2 => STDERR,
  21. );
  22. $cmd = "exec {$php_executable} -t {$doc_root} $ini -S " . PHP_CLI_SERVER_ADDRESS . " 2>/dev/null";
  23. $handle = proc_open($cmd, $descriptorspec, $pipes, $doc_root);
  24. }
  25. // note: even when server prints 'Listening on localhost:8964...Press Ctrl-C to quit.'
  26. // it might not be listening yet...need to wait until fsockopen() call returns
  27. $error = "Unable to connect to server\n";
  28. for ($i=0; $i < 60; $i++) {
  29. usleep(50000); // 50ms per try
  30. $status = proc_get_status($handle);
  31. $fp = @fsockopen(PHP_CLI_SERVER_HOSTNAME, PHP_CLI_SERVER_PORT);
  32. // Failure, the server is no longer running
  33. if (!($status && $status['running'])) {
  34. $error = "Server is not running\n";
  35. break;
  36. }
  37. // Success, Connected to servers
  38. if ($fp) {
  39. $error = '';
  40. break;
  41. }
  42. }
  43. if ($fp) {
  44. fclose($fp);
  45. }
  46. if ($error) {
  47. echo $error;
  48. proc_terminate($handle);
  49. exit(1);
  50. }
  51. register_shutdown_function(
  52. function($handle) {
  53. proc_terminate($handle);
  54. /* Wait for server to shutdown */
  55. for ($i = 0; $i < 60; $i++) {
  56. $status = proc_get_status($handle);
  57. if (!($status && $status['running'])) {
  58. break;
  59. }
  60. usleep(50000);
  61. }
  62. },
  63. $handle
  64. );
  65. }
  66. ?>