PHP provides the mail() function for easy sending of mail from your PHP server. The problem is that sending HTML email (the most popular format for emails) is not easily done using native PHP functions. I’ve provided below a somewhat foolproof function that will allow you to send HTML emails.
Simply pass in a to address, from address, from name (which is used as a nickname in email clients instead of displaying the sender’s email address), subject, and a properly formatted HTML email message.
If you are sending to multiple recipients, you can pass the $to_email parameter in as an array of multiple email addresses.
HTML Email Function
function send_email ($to_email, $from_email, $from_name, $subject, $msg) {
//split up to email array, if given
if (is_array($to_email)) {
$to_email_string = implode(', ', $to_email);
}
else {
$to_email_string = $to_email;
}
//Assemble headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $from_name <$from_email>" . "\r\n";
//send via PHP's mail() function
mail($to_email_string, $subject, $msg, $headers);
}
Usage
You call the function like this:
send_email("me@gmail.com", "roger@att.com", "Roger", "Hello There",
"<html>Hello There <strong>Bob</strong>! How are you doing</html>!");
Or, alternately, you call it like this when sending to multiple email addresses:
send_email(array("me@gmail.com", "sal@gmail.com"), "roger@att.com", "Roger",
"Hello There", "<html>Hello There <strong>Bob</strong>! How are you doing</html>!");
HTML Email Formatting
Remember that formatting HTML for email is different than for webpages. Do not use a CSS file and do not declare CSS in the head of your document. Instead, use either inline CSS or “Old School” HTML like font tags for formatting. Also, don’t use JavaScript, as major email clients don’t support it.
Though it may seem obvious, remember that images and links within your HTML email need to be full, absolute paths to their world wide web accessible location. No relative links!
Here’s another PHP function I cannot live without - I add this into my standard PHP functions include on all projects. Often when displaying text, I am forced to abbreviate the text to a certain number of characters. You might jump in a decide to use substring() on your text to achieve this abbreviation, but that can cause several problems. The most blatant is that you will often split the text right in the middle of a word. In addition, if there are any HTML tags in the text, they could get cut in the middle too, or have the closing tag left off completely, potentially breaking the display or exposing the remaining part of the tag.
As a solution to these problems, I have written a function that only trims on the last space before the number of characters you specify, so it will never cut words in half. Also, it strips out HTML tags before doing the character trim, preventing possible display issues. And, as a convenience it adds ellipses (the …) to all trimmed text, as a visual cue to the reader that the text has been abbreviated.
<?php
/**
* trims text to a space then adds ellipses if desired
* @param string $input text to trim
* @param int $length in characters to trim to
* @param bool $ellipses if ellipses (...) are to be added
* @param bool $strip_html if html tags are to be stripped
* @return string
*/
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
?>
MY Common PHP Includes
When I start a new application or website, I always start with the same framework of files. I have a series of include files that I include as necessary on pages (scripts) on the site. Stuff like site navigation, database connection, and core functions are some of the includes I use.
My functions include has all the functions that I’m confident are going to be used frequently enough on the site to warrant their inclusion (and subsequent declaration) in every script in the site. While most of the functions vary from site, because they relate to a specific feature or concept that the site incorporates, there are two functions that I always include.
My Get and Post Functions
All my sites and applications are dynamic, which means they receive input from the user using either the GET or POST method. If you incorporate forms into your site, you’re probably familiar with GET and POST and the differences between the two. One thing I noticed after some time programming was that handling data through GET and POST was done frequently and could be easily compartmentalized in two simple helper functions.
Below is my implementation of these functions:
<?php
function getData($var, $maxLength=99999) {
$value = NULL;
if (isset($_GET[$var])) {
$value = trim(htmlentities($_GET[$var], ENT_QUOTES));
if (strlen($value) > $maxLength) {
$value = substr($value, 0, $maxLength);
}
}
return $value;
}
function postData($var, $maxLength=99999) {
$value = NULL;
if (isset($_POST[$var])) {
$value = trim(htmlentities($_POST[$var], ENT_QUOTES));
if (strlen($value)>$maxLength) {
$value = substr($value, 0, $maxLength);
}
}
return $value;
}
?>
These functions act as helper functions to retrieve the value that was sent to the script and available to PHP’s global $_GET and $_POST arrays. They also implement a few simple extra features. When calling either of these two functions, you can also supply a $maxLength parameter, which would be the maximum expected length of that variable. If anything is longer, then someone may be trying to take advantage of your website by sending data not in the way you intended. If the variable is longer than expected, the function still allows it, though it trims it to the length you are expecting. This can be helpful if you are inserting values into a database that has limits on the number of characters in a field. In addition, the function also puts the value through PHP’s htmlentities() function which will encode each character into their html equivalent, which I almost always need. This can also disarm any injected code that a malicious user may be sending to your script. Lastly, the function returns NULL when the expected variable has not been passed. This allows easy error handling when calling this function. Here is an example of doing error handling when retrieving a function:
<?php
//Attempt to retrieve the value
$username = getData('username');
if ($username == false) {
//This value does not exist, do something to handle this situation
}
else {
echo 'Welcome ' . $username . '!';
}
?>
|
|
Warning: include() [ function.include]: URL file-access is disabled in the server configuration in /home/content/b/r/u/brueggemanwine/html/blog/wp-content/themes/ebrue_theme/footer.php on line 51
Warning: include(http://www.ebrueggeman.com/includes/include_ad_chooser.php) [ function.include]: failed to open stream: no suitable wrapper could be found in /home/content/b/r/u/brueggemanwine/html/blog/wp-content/themes/ebrue_theme/footer.php on line 51
Warning: include() [ function.include]: Failed opening 'http://www.ebrueggeman.com/includes/include_ad_chooser.php' for inclusion (include_path='.:/usr/local/php5/lib/php') in /home/content/b/r/u/brueggemanwine/html/blog/wp-content/themes/ebrue_theme/footer.php on line 51
|