1
- <?php
2
-
3
- define ("PHP_CURL_SERVER_HOSTNAME " , "localhost " );
4
- define ("PHP_CURL_SERVER_PORT " , 8964 );
5
- define ("PHP_CURL_SERVER_ADDRESS " , PHP_CURL_SERVER_HOSTNAME .": " .PHP_CURL_SERVER_PORT );
1
+ <?php declare (strict_types=1 );
6
2
7
3
function curl_cli_server_start () {
8
4
if (getenv ('PHP_CURL_HTTP_REMOTE_SERVER ' )) {
@@ -12,21 +8,50 @@ function curl_cli_server_start() {
12
8
$ php_executable = getenv ('TEST_PHP_EXECUTABLE ' );
13
9
$ doc_root = __DIR__ ;
14
10
$ router = "responder/get.inc " ;
15
- $ cmd = [$ php_executable , '-t ' , $ doc_root , '-n ' , '-S ' , PHP_CURL_SERVER_ADDRESS , $ router ];
11
+ $ cmd = [$ php_executable , '-t ' , $ doc_root , '-n ' , '-S ' , ' localhost:0 ' , $ router ];
16
12
$ descriptorspec = array (
17
13
0 => STDIN ,
18
14
1 => STDOUT ,
19
- 2 => array ( " null " ) ,
15
+ 2 => [ ' pipe ' , ' w ' ] ,
20
16
);
21
17
$ handle = proc_open ($ cmd , $ descriptorspec , $ pipes , $ doc_root , null , array ("suppress_errors " => true ));
22
18
19
+ // First, wait for the dev server to declare itself ready.
20
+ $ bound = null ;
21
+ stream_set_blocking ($ pipes [2 ], false );
22
+ for ($ i = 0 ; $ i < 60 ; $ i ++) {
23
+ usleep (50000 ); // 50ms per try
24
+ $ status = proc_get_status ($ handle );
25
+ if (empty ($ status ['running ' ])) {
26
+ echo "Server is not running \n" ;
27
+ proc_terminate ($ handle );
28
+ exit (1 );
29
+ }
30
+
31
+ while (($ line = fgets ($ pipes [2 ])) !== false ) {
32
+ if (preg_match ('@PHP \S* Development Server \(https?://(.*?:\d+)\) started@ ' , $ line , $ matches )) {
33
+ $ bound = $ matches [1 ];
34
+ // Now that we've identified the listen address, close STDERR.
35
+ // Otherwise the pipe may clog up with unread log messages.
36
+ fclose ($ pipes [2 ]);
37
+ break 2 ;
38
+ }
39
+ }
40
+ }
41
+ if ($ bound === null ) {
42
+ echo "Server did not output startup message " ;
43
+ proc_terminate ($ handle );
44
+ exit (1 );
45
+ }
46
+
47
+ // Now wait for a connection to succeed.
23
48
// note: even when server prints 'Listening on localhost:8964...Press Ctrl-C to quit.'
24
49
// it might not be listening yet...need to wait until fsockopen() call returns
25
50
$ error = "Unable to connect to server \n" ;
26
51
for ($ i =0 ; $ i < 60 ; $ i ++) {
27
52
usleep (50000 ); // 50ms per try
28
53
$ status = proc_get_status ($ handle );
29
- $ fp = @fsockopen (PHP_CURL_SERVER_HOSTNAME , PHP_CURL_SERVER_PORT );
54
+ $ fp = @fsockopen (" tcp:// $ bound " );
30
55
// Failure, the server is no longer running
31
56
if (!($ status && $ status ['running ' ])) {
32
57
$ error = "Server is not running \n" ;
@@ -64,5 +89,5 @@ function curl_cli_server_start() {
64
89
$ handle
65
90
);
66
91
67
- return PHP_CURL_SERVER_ADDRESS ;
92
+ return $ bound ;
68
93
}
0 commit comments