|
97 | 97 | }; |
98 | 98 |
|
99 | 99 | function send_response_chunk($data) { |
100 | | - global $is_chunked_response; |
101 | | - if ($is_chunked_response) { |
| 100 | + if (should_send_as_chunked_response()) { |
| 101 | + // We need to manually chunk the response when running in the PHP |
| 102 | + // built-in server. It won't handle that for us. |
102 | 103 | echo sprintf("%s\r\n%s\r\n", dechex(strlen($data)), $data); |
103 | 104 | } else { |
| 105 | + // When running behing an Apache or Nginx or another webserver, |
| 106 | + // it will handle the chunking for us. Manually sending the chunk |
| 107 | + // header, \r\n separator, body, and \r\n trailer isn't just |
| 108 | + // unnecessary, but it would actually include those bytes in the |
| 109 | + // response body. |
104 | 110 | echo $data; |
105 | 111 | } |
106 | 112 | @ob_flush(); |
107 | 113 | @flush(); |
108 | 114 | } |
109 | 115 |
|
| 116 | +/** |
| 117 | + * We need to manually chunk the response when running the PHP |
| 118 | + * dev server AND the transfer-encoding header is set to chunked. |
| 119 | + * |
| 120 | + * Apache, Nginx, etc. will handle the chunking for us. |
| 121 | + */ |
| 122 | +function should_send_as_chunked_response() { |
| 123 | + global $is_chunked_response; |
| 124 | + return $is_chunked_response && php_sapi_name() === 'cli-server'; |
| 125 | +} |
| 126 | + |
110 | 127 | // Pin the hostname resolution to an IP we've resolved earlier |
111 | 128 | curl_setopt($ch, CURLOPT_RESOLVE, [ |
112 | 129 | "$host:80:$resolvedIp", |
@@ -255,7 +272,9 @@ function( |
255 | 272 | // Close cURL session |
256 | 273 | curl_close($ch); |
257 | 274 |
|
258 | | -// Only send chunked transfer encoding footer if we're using chunked encoding |
259 | | -if ($is_chunked_response) { |
| 275 | +// Only send chunked transfer encoding footer if we're using chunked encoding. |
| 276 | +// We need to manually send the footer when running in the PHP built-in server |
| 277 | +// because, unlike apache or nginx, it won't handle that for us. |
| 278 | +if (should_send_as_chunked_response()) { |
260 | 279 | echo "0\r\n\r\n"; |
261 | 280 | } |
0 commit comments