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