php_cli_server.inc 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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";', $router = 'index.php', $cmd_args = null) {
  6. $php_executable = getenv('TEST_PHP_EXECUTABLE');
  7. $doc_root = __DIR__;
  8. if ($code) {
  9. file_put_contents($doc_root . '/' . ($router ?: 'index.php'), '<?php ' . $code . ' ?>');
  10. }
  11. if (substr(PHP_OS, 0, 3) == 'WIN') {
  12. $descriptorspec = array(
  13. 0 => STDIN,
  14. 1 => STDOUT,
  15. 2 => array("pipe", "w"),
  16. );
  17. $cmd = "{$php_executable} -t {$doc_root} -n {$cmd_args} -S " . PHP_CLI_SERVER_ADDRESS;
  18. if (!is_null($router)) {
  19. $cmd .= " {$router}";
  20. }
  21. $handle = proc_open(addslashes($cmd), $descriptorspec, $pipes, $doc_root, NULL, array("bypass_shell" => true, "suppress_errors" => true));
  22. } else {
  23. $descriptorspec = array(
  24. 0 => STDIN,
  25. 1 => STDOUT,
  26. 2 => STDERR,
  27. );
  28. $cmd = "exec {$php_executable} -t {$doc_root} -n {$cmd_args} -S " . PHP_CLI_SERVER_ADDRESS;
  29. if (!is_null($router)) {
  30. $cmd .= " {$router}";
  31. }
  32. $cmd .= " 2>/dev/null";
  33. $handle = proc_open($cmd, $descriptorspec, $pipes, $doc_root);
  34. }
  35. // note: even when server prints 'Listening on localhost:8964...Press Ctrl-C to quit.'
  36. // it might not be listening yet...need to wait until fsockopen() call returns
  37. $error = "Unable to connect to server\n";
  38. for ($i=0; $i < 60; $i++) {
  39. usleep(50000); // 50ms per try
  40. $status = proc_get_status($handle);
  41. $fp = @fsockopen(PHP_CLI_SERVER_HOSTNAME, PHP_CLI_SERVER_PORT);
  42. // Failure, the server is no longer running
  43. if (!($status && $status['running'])) {
  44. $error = "Server is not running\n";
  45. break;
  46. }
  47. // Success, Connected to servers
  48. if ($fp) {
  49. $error = '';
  50. break;
  51. }
  52. }
  53. if ($fp) {
  54. fclose($fp);
  55. }
  56. if ($error) {
  57. echo $error;
  58. proc_terminate($handle);
  59. exit(1);
  60. }
  61. register_shutdown_function(
  62. function($handle) use($router) {
  63. proc_terminate($handle);
  64. @unlink(__DIR__ . "/{$router}");
  65. },
  66. $handle
  67. );
  68. return $handle;
  69. }
  70. function php_cli_server_stop($handle) {
  71. $success = FALSE;
  72. if ($handle) {
  73. proc_terminate($handle);
  74. /* Wait for server to shutdown */
  75. for ($i = 0; $i < 60; $i++) {
  76. $status = proc_get_status($handle);
  77. if (!($status && $status['running'])) {
  78. $success = TRUE;
  79. break;
  80. }
  81. usleep(50000);
  82. }
  83. }
  84. return $success;
  85. }
  86. ?>