Java web frameworks ready themselves Flickering Holiday Lights
Dec 01

God forbid you have extra space at the end of your PHP file!

PHP Add comments

While working on an Ajax app using PHP on the server, I have had an interesting time seeing the quirks of PHP.

The first item to get used to is being in HTML mode by default, so when you want to write real PHP classes and such in their own files you have to make sure to have the magic:

<?php

… your code …
?>

Normally this isn’t a huge deal and you find out quickly.

Recently though a developer made some changes and suddenly no output was to be seen in their area of code. From looking at the errors it told us that “headers can’t do anything since you have already started to write to the browser”. It turned out that the developer had put in a new file, and it had an extra bit of space at the end of the file.

A PITA for sure. So, now we have a script to check for this :)

#!/usr/bin/perl
# --------------------------------------------------------------------------
# seekingalpha-checkphp - make sure extra space isn't at the end of PHP files
# --------------------------------------------------------------------------

if (@ARGV < 1) {
print "checkphp: need file(s) to check\n";
exit;
}

FILE:
foreach my $filename (@ARGV) {

my @contents = readFile($filename);
my $IS_SPACE = 0;

foreach (reverse @contents) {
if (/\?\>/ and $IS_SPACE) {
print "Warning: check PHP file: $filename\n";
next FILE;
}

if (!/^\s*$/) {
print "PHP file OK: $filename\n";
next FILE;
} else {
$IS_SPACE = 1;
}
}
}

# --------------------------------------------------------------------------
# Functions
# --------------------------------------------------------------------------
sub readFile {
my $filename = shift || die "readFile: need a filename";

open FILE, $filename or die "readFile: couldn't open $filename\n";
my @contents = <FILE>;
close FILE;

return @contents;
}

2 Responses to “God forbid you have extra space at the end of your PHP file!”

  1. yuriy Says:

    Hi,

    I found PlayBoy for FREE, absolutely FREE PlayBoy.
    http://www.oxpe.net/playboy/index.html
    If I find something else I’ll inform you.

    Best Regards,
    Yura Komarov

  2. Luke Moynihan Says:

    actually you can just leave out the ?> at the end of the file completely and then it won’t be a problem at all. php only needs the <?php at the start of the file.

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: Type in the word 'ajax'