WordPress Image Crop Disabled, or Finding PHP Files with Trailing Space

One of our many wordpresses was not allowing you to crop images. I tracked this down to the image failing to load which in turn was caused by an extra \r\n preceding the image content. This extra line-break is caused when an included php file ends in ?>\r\n. Because php writes any content outside of a php tag to the output stream, this causes an extra newline to precede any other content you might have been trying to send (such as a jpeg image). This can cause all sorts of problems, in this case corrupting the JPEG output.

To fix this problem I investigated how to get grep to search in multiline mode (install pcregrep). I then had the trouble that $ matches end of line rather than end of file. After some googling I found that \z will match end of file, and with that I was off to the races. This pcregrep expression will allow you to find php files with pesky trailing space issues.

pcregrep -Mri --exclude_dir=.svn --exclude_dir=css '\?>\s+\z' wp-content/plugins

The offending plugin in my case was an older version of wp-e-commerce (which is not easily upgradeable). After finding all the files with trailing whitespace and removing it, I could now crop images in wordpress again.