To close or not to close php

The question:

I have read that it is advised (especially with php 7) to not close the php files with ?>

Many of my WP php files end like this:

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Should I remove the closing tag and have something like this

<?php get_sidebar(); ?>
<?php get_footer(); 

at the end of my files?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Yes, please avoid closing PHP tags at the end of the file, not only with PHP 7, but with PHP 5 as well.

Reason is that if you close the tag, anything that is after the tag, even a blank line, will be sent to output and will make PHP to send headers as well preventing cookie to be set, redirect to work, feed to be valid, and so on.

I guess that you ever encountered a message like

Cannot modify header information – headers already sent by (output started at …) in … on line …

A closing ?> at end of the file can be the cause.

Method 2

Given your specific example, I would keep the closing tag i.e. one-line function calls within a template. It’s consistent and aids clarity (in the same way WordPress recommend trailing commas for arrays)- otherwise imagine if a non-developer picked up your file and started adding to it:

<?php get_footer();

<div>What the hell am I doing wrong?</div>

However, for all other files (functions, includes etc.), the advice is most definitely a good idea:

<?php // Start of file

class MY_Class {
    function just_do_it() {

// Bye bye closing tag

I find it’s cleaner, and as other’s have mentioned, no risk of the dreaded “headers already sent”.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment