Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CORS Proxy] Support chunked encoding when running in Apache/Nginx/etc #2114

Open
wants to merge 2 commits into
base: trunk
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions packages/playground/php-cors-proxy/cors-proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,33 @@
};

function send_response_chunk($data) {
global $is_chunked_response;
if ($is_chunked_response) {
if (should_send_as_chunked_response()) {
// We need to manually chunk the response when running in the PHP
// built-in server. It won't handle that for us.
echo sprintf("%s\r\n%s\r\n", dechex(strlen($data)), $data);
} else {
// When running behing an Apache or Nginx or another webserver,
// it will handle the chunking for us. Manually sending the chunk
// header, \r\n separator, body, and \r\n trailer isn't just
// unnecessary, but it would actually include those bytes in the
// response body.
echo $data;
}
@ob_flush();
@flush();
}

/**
* We need to manually chunk the response when running the PHP
* dev server AND the transfer-encoding header is set to chunked.
*
* Apache, Nginx, etc. will handle the chunking for us.
*/
function should_send_as_chunked_response() {
global $is_chunked_response;
return $is_chunked_response && php_sapi_name() === 'cli-server';
}

// Pin the hostname resolution to an IP we've resolved earlier
curl_setopt($ch, CURLOPT_RESOLVE, [
"$host:80:$resolvedIp",
Expand Down Expand Up @@ -255,7 +272,9 @@ function(
// Close cURL session
curl_close($ch);

// Only send chunked transfer encoding footer if we're using chunked encoding
if ($is_chunked_response) {
// Only send chunked transfer encoding footer if we're using chunked encoding.
// We need to manually send the footer when running in the PHP built-in server
// because, unlike apache or nginx, it won't handle that for us.
if (should_send_as_chunked_response()) {
echo "0\r\n\r\n";
}
Loading