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