Archive for January 2nd, 2012

PHP Mail Function and the New Line Character

Lately I have come to the notion that I can modularize my PHP and inject it like a serum into some of my older websites to update and upgrade their performance and useability. In pursuit of this goal, I rewrote a mail utility to make it universal, a kind of plugin. Simply FTP some files to the server, install a link and wham.

I put the utility on Drywall How To Manual. It works great…now. There was only one tiny problem. When I rewrote the utility, I changed the $message variable to look something like this:

$message = “Name: $cname \n Email: $cemail \n Ref Page: $ref_url \n Message: $cmessage \n”;

It feeds the following:

$mail_success = mail($email, $subject, $message);

Do you see anything wrong with it? Neither did I. It took me an hour of testing and breaking down those lines of code to find out what the problem was.  I will give you a hint if you haven’t already got an inkling from the title of this post. The problem is in the new line character.

Yes, you can have a new line character in the variable of the mail function in PHP. Only thing is you cannot have it at the end JUST BEFORE the quote mark.

The funny thing is that this does not throw an error. In fact, the email is simply not sent, but the function returns “true”, indicating the message was sent.

To test to make sure that the “backslant n” was not a general no no in PHP I tried a little test which looked like this:

//test in variable:
$test = “test \n”;
$test2 = “test2 \n”;
print “test = $test”;
print “test2 = $test2″;
print “test3″;
print “\n”;

//test in function:
$length = strlen($test);
print “length = $length”;

The results make me believe this is a little bug in the mail() function:

test = test
test2 = test2
length = 6

Interesting development. No matter how long you are in the game, you always are learning something.

No Comments