xref: /PHP-5.5/sapi/cli/tests/php_cli_server.inc (revision 0cc28104)
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') {
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	$descriptorspec = array(
15		0 => STDIN,
16		1 => STDOUT,
17		2 => STDERR,
18	);
19
20	if (substr(PHP_OS, 0, 3) == 'WIN') {
21		$cmd = "{$php_executable} -t {$doc_root} -n -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		$cmd = "exec {$php_executable} -t {$doc_root} -n -S " . PHP_CLI_SERVER_ADDRESS;
29		if (!is_null($router)) {
30			$cmd .= " {$router}";
31		}
32		$cmd .= " 2>/dev/null";
33
34		$handle = proc_open($cmd, $descriptorspec, $pipes, $doc_root);
35	}
36
37	// note: even when server prints 'Listening on localhost:8964...Press Ctrl-C to quit.'
38	//       it might not be listening yet...need to wait until fsockopen() call returns
39    $i = 0;
40    while (($i++ < 30) && !($fp = @fsockopen(PHP_CLI_SERVER_HOSTNAME, PHP_CLI_SERVER_PORT))) {
41        usleep(10000);
42    }
43
44    if ($fp) {
45        fclose($fp);
46    }
47
48	register_shutdown_function(
49		function($handle) use($router) {
50			proc_terminate($handle);
51			@unlink(__DIR__ . "/{$router}");
52		},
53			$handle
54		);
55	// don't bother sleeping, server is already up
56	// server can take a variable amount of time to be up, so just sleeping a guessed amount of time
57	// does not work. this is why tests sometimes pass and sometimes fail. to get a reliable pass
58	// sleeping doesn't work.
59}
60?>
61
62