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