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