php_cli_server.inc 2.0 KB

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