Skip to content

http_response_code should warn if headers already sent #10744

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

Closed
Closed
Show file tree
Hide file tree
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
12 changes: 12 additions & 0 deletions ext/standard/head.c
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,18 @@ PHP_FUNCTION(http_response_code)

if (response_code)
{
if (SG(headers_sent) && !SG(request_info).no_headers) {
const char *output_start_filename = php_output_get_start_filename();
int output_start_lineno = php_output_get_start_lineno();

if (output_start_filename) {
php_error_docref(NULL, E_WARNING, "Cannot set response code - headers already sent "
"(output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL, E_WARNING, "Cannot set response code - headers already sent");
}
RETURN_FALSE;
}
zend_long old_response_code;

old_response_code = SG(sapi_headers).http_response_code;
Expand Down
11 changes: 10 additions & 1 deletion ext/standard/tests/general_functions/http_response_code.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,17 @@ var_dump(
// Get the new response code
http_response_code()
);
echo "Now we've sent the headers\n";
var_dump(
// This should fail
http_response_code(500)
);
?>
--EXPECT--
--EXPECTF--
bool(false)
bool(true)
int(201)
Now we've sent the headers

Warning: http_response_code(): Cannot set response code - headers already sent (output started at %s:%d) in %s on line %d
bool(false)
4 changes: 2 additions & 2 deletions sapi/fpm/tests/log-suppress-output.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function doTestCalls(FPM\Tester &$tester, bool $expectSuppressableEntries)
$tester->request(query: 'test=output', uri: '/ping')->expectBody('pong', 'text/plain');
$tester->expectAccessLog("'GET /ping?test=output' 200", suppressable: false);

$tester->request(headers: ['X_ERROR' => 1])->expectBody('Not OK');
$tester->request(headers: ['X_ERROR' => 1])->expectStatus('500 Internal Server Error')->expectBody('Not OK');
$tester->expectAccessLog("'GET /log-suppress-output.src.php' 500", suppressable: false);

$tester->request()->expectBody('OK');
Expand All @@ -54,8 +54,8 @@ function doTestCalls(FPM\Tester &$tester, bool $expectSuppressableEntries)
$src = <<<EOT
<?php
if (isset(\$_SERVER['X_ERROR'])) {
echo "Not OK";
http_response_code(500);
echo "Not OK";
exit;
}
echo \$_REQUEST['test'] ?? "OK";
Expand Down