DEV Community

Avdi Grimm
Avdi Grimm

Posted on • Originally published at avdi.codes on

1

Be careful of whitespace in .php files

So I was debugging some anomalous behavior on my website and as I was poking around, I half-consciously noticed the change bars in in my editor that showed two extra newlines at the end of a .php file. But I dismissed this even as soon as I saw it because… I mean, it's just whitespace. At the end of a file.

Literally just whitespace at the end of a file, outside of any code.

Later I noticed a warning in the logs about “Cannot Modify Header Information”. And it was just a warning, but I didn't remember seeing it before, so I did some googling. And what I read reminded me that the way PHP works is that it tries to emit anything outside <?php ?> flags back to the web browser.

“What the heck” I thought, and removed the newlines. Immediately the site started to work again.

Bug fix: remove newlines

So lesson learned: watch out for whitespace in .php files.

This also made something else I'd seen in PHP-land make more sense. I'd noticed that some authors leave the closing ?> off of the end of files that contain only PHP code and no HTML. This offended the well-formedness centers of my brain, and I'd previously written it off as laziness. But now I understand that this is idiomatic, and for good reasons.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay