2009-11-23

PHP 102: Whitespace Matters!

Lets start at the beginning. Lets start with creating a blank PHP script. What's one of the most important things to remember when creating a new PHP script? I'll tell ya: Whitespace Matters!

You must keep track of your whitespace in PHP scripts. Why? HTTP headers cannot be set if you have already "printed" any characters. Stray spaces before and after segments will, among other things, prevent you from setting HTTP headers (e.g. session cookies, redirects, and so on).

This is something I run into over and over and over and over in modifying carelessly written code. Sometimes this is the work of a well intentioned developer trying to make code "more readable". Worse, this is a problem you won't catch until its too late. You can code for months or years on a project and never notice any problems. Until one day everything explodes for no obvious reason. There are huge, massive projects out there that still haven't completely learned this lesson.

Opening Demarcation
If your script contains only PHP code then it must begin with <?php at the very beginning of the file. No spaces. No new lines. <?php should be the very first characters in your new file. Don't use asptags <%, don't use shorttags <? or any other cutesy business.

Closing Demarcation
If your script contains only code and no embedded HTML markup then it must never include a ?> closing tag. Never. Ever. Yes, of course it'll work. Don't do it. Omitting the closing ?> ensures that all trailing whitespace will be in a code segment and not your output buffer.

Good Example
<?php
function helloWorld(){
return 'Hello World!';
}

echo helloWorld();



Bad Example



<?php
function helloWorld(){
return 'Hello World!';
}

echo helloWorld();

?>

Labels: , ,

2009-06-04

php-imap extension == evil

The Problem

The PHP IMAP extension relies on University of Washington's libc-client IMAP library which appears to be written by kindergarteners. After some review of the source code, UW's IMAP client library appears to have extensive, serious security and stability problems at very fundamental levels.

I'm seeing segfaults (buffer overflows) performing simple operations like fetching attachments. Some attachments work fine but others fail; larger files especially. There are bug reports and CVE entries related to similar issues. However, upgrading to the supposed "fixed" versions of everything does not make any difference for my specific issue. It does fix some other issues related to this. (i.e. the exact same programming errors that appear to affect thousands of lines of code in the UW client.)

The Solution

Use one of the many native IMAP class library. My choice would be Zend_Mail as we use Zend Framework extensively here at work. Zend_Mail supports a number of other mail protocols in addition to IMAP. MIME type support is likely much better than other options. The other logical choice would be Pear Net_IMAP.

Labels: , , ,