Closing Tag In Php Only File

ID

php.closing_php_tag

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Php

Tags

code_smell, portability

Description

Reports a trailing closing tag ?> at the end of a file that contains only PHP code. Files that intermix HTML output sections are left untouched, because there the closing tag is required.

Rationale

In a file made up entirely of PHP, the closing ?> tag adds no value and creates a subtle hazard: any character — most commonly a stray newline or space — placed after the tag is sent straight to the output stream. That early output makes later header() or setcookie() calls fail with a "headers already sent" error and corrupts binary responses such as generated images or downloads. Omitting the tag removes the entire class of problem, which is why the community style guides require it to be left out of pure-PHP files.

<?php
declare(strict_types=1);

function greet(string $name): string
{
    return "Hello, " . $name;
}

echo greet("World");
?>

The file above is pure PHP, so the final ?> is reported. Removing it (and any whitespace that follows) resolves the issue. A template file that emits HTML keeps its closing tags untouched.

Remediation

Delete the trailing ?> tag, together with any whitespace that follows it, from files that contain only PHP.