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