The Case of the Non-missing Newline
- you can do in principle do anything you want with any language,
- PHP is designed for producing html pages to be sent to the browser,
- Python is designed to be easy to understand, without as much of a specialty.
Probably 80% of the code I’ve written for the site is in PHP. The special power of PHP is to put little function calls inside fixed text, which is useful for generating web pages. Here’s an example, which you can imagine as part of the text of an .html file:
<div>The time is <?php echo time(); ?> and my lucky number is <?php 3+4; ?>.</div>
This will print out the current time as part of the .html page whenever it is accessed.
I found that there was a jam session for PHP taking place in my area tonight. Pretty random sounding, but it’s always good to find things out from people with more experience. I asked some questions about sandboxing and grid displays and got some good suggestions for further investigation. Apparently “frameworks” are all the rage but I am not caught up to speed on that yet. Fast forward to the one snippet of code which someone wrote on the whiteboard,
<?php echo "Hello, World!";
Pretty trivial, but very useful! I never really thought to notice, but the end of the file makes a big difference. You can include a
?> or leave it out like the second example shows.
So tonight, without asking anyone, the cause of the bug was revealed! Hello World solved all my problems. The bug happens when you
- leave the
?>at the end of the file
- put a newline after the ?>, which causes the newline to be printed out since it’s outside of <?php … ?>, and
In retrospect I knew all of these facts but it’s pretty subtle. I can’t think of any other programming I’ve done where I would even imagine that a newline at the end of file could make a difference.
It’s satisfying to finally fix the bug and remove the old hack… like a stupidity epiphany! If you want a script to detect this problem automatically, check out the page “God forbid you have extra space at the end of your PHP file!“. Guess I am not alone in my epiphany.
Filed under: php, programming, wordpress | 2 Comments