Print Object

There have been numerous times where I've needed to print out the contents of an object or an array in order to debug things while I've been developing a script. There is the print_r() that is built into PHP. But that doesn't print things in a very user friendly fashion unless you're looking at the source code. I don't always want to look at the source code just to see the contents of the array or object. So I put together a function that wraps the print_r() within <pre> tags so that I can view the contents easily within the page.

POST/GET/REQUEST Functions

In some of the sections of my websites, I need to get parameters either from the query string or posted to the page by a form so I can use them as needed. I have created a few functions to do just that.

Get the value of a parameter posted to the page.

Source Code:
<?php
function get_post($param
{
    
$value $_POST[$param];
    return 
$value;
}
?>
Example:
<?php 
$name 
get_post("name");
print 
"Hello {$name}"
?>

Get the value of a parameter from the query string.

Source Code:
<?php
function get_get($param
{
    
$value $_GET[$param];
    return 
$value;
}
?>
Example:
<?php
$multiplier 
get_get("token");
$new_value 10 $multiplier;
print 
"10 x {$multiplier} = {$new_value}";
?>

Get the value of a parameter posted to the page OR from the query string. NOTE: This function can take the place of both of the previous two functions.

Source Code:
<?php
function get_request($param
{
    
$value $_REQUEST[$param];
    return 
$value;
}
?>
Example:
<?php
$id 
get_request("id");
$sql "SELECT * FROM tblResults WHERE ResultID = {$id}";
?>

MySQL Database Connection Class

All of my personal websites utilize a MySQL database. To help with connecting to the database, I created a database connection class. This class connects to the database server and selects the specified database. It also contains functions to execute a SQL query and loop through the results of that query.

Source Code:
<?php
/**
 * @brief This class contains the functions used to connect to a mysql database.
 * @author Becky Resler <becky@hightechredneckwoman.com>
 * @version 1.0 - 04/27/2005 Original Version.
 * @copyright 2005 Becky Resler http://www.hightechredneckwoman.com
 * 
 * CHANGELOG:
 * version 1.0 - 04/27/2005 Original Version.
 */

class mysql_connection 
{
    private 
$_dbhost;
    private 
$_dbusername;
    private 
$_dbpasswd;
    private 
$_database_name;
    private 
$_dbConnectionID;
    private 
$_queryID;
    private 
$_record;
    
/**
     * @brief This function sets up the class.
     * @param string - $dbhost - The database host.
     * @param string - $dbusername - The database username.
     * @param string - $dbpasswd - The database password.
     * @param string - $database_name - The database name.
     * @return bool - true if successfully connected to database; otherwise false.
     */
    
public function __construct($dbhost$dbusername$dbpasswd$database_name
    {
        
$this->_dbhost          $dbhost;
        
$this->_dbusername      $dbusername;
        
$this->_dbpasswd        $dbpasswd;
        
$this->_database_name   $database_name;
        
        
// connect to the database
        
if($this->_connect() !== true)
            return 
false;
        
        return 
true;
    }
    
/**
     * @brief This function executes a query.
     * @param string - $sql - The query to be executed.
     */
    
public function execute($sql
    {
        if(empty(
$this->_dbConnectionID))
        {
            if(
$this->_connect() !== true)
                return 
false;
        }
        
$this->_queryID = @mysql_query($sql$this->_dbConnectionID);
        if(
$this->_queryID === false)
        {
            
error_log("mysql_connection::execute() -- SQL = {$sql}, Error = ".mysql_errno().":".mysql_error());
            return 
false;
        }        
        return 
true;
    }
    
/**
     * @brief This function moves the recordset to the next record.
     * @return bool - $status - A flag indicating if there is a record.
     */
    
public function nextRecord()
    {
        
$this->_record  = @mysql_fetch_array($this->_queryID);
        
$status         is_array($this->_record);
        
        return 
$status;
    }    
    
/**
     * @brief This function gets the number of rows in the recordset.
     * @return int - $rows - The number of rows.
     */
    
public function numRows()
    {
        
$rows = @mysql_num_rows($this->_queryID);
        
        return 
$rows;
    }    
    
/**
     * @brief This function gets the value for the specified field in the current record.
     * @param string - $field - The name of the field.
     * @return mixed - $value - The value of the specified field.
     */
    
public function getField($field)
    {
        
$value $this->_record[$field];
        
        return 
$value;
    }
    
    
/**
     * @brief This function creates a connection to the database.
     * @return bool - true if connects successfully; otherwise false.
     */
    
private function _connect() 
    {
        
// connect to the database server
        
$this->_dbConnectionID = @mysql_pconnect($this->_dbhost$this->_dbusername$this->_dbpasswd);
        if(
$this->_dbConnectionID === false)
        {
            
error_log("mysql_connection::_connect() -- ".mysql_errno().":".mysql_error());
            return 
false;
        } 
        else 
        {
            
// select the specified database
            
if(@mysql_select_db($this->_database_name$this->_dbConnectionID) !== true
            {
                
error_log("mysql_connection::_connect() -- ".mysql_errno().":".mysql_error());
                return 
false;
            }
        }
        
        return 
true;
    }
}
?>
Example:
<?php
require_once "cls_mysql_connection.php";
$db = new mysql_connection("localhost","USERNAME","PASSWORD","DATABASE_NAME");
$sql "SELECT ResultID, ResultValue FROM tblResults ORDER BY ResultDate DESC";
$db->execute($sql);
while(
$db->nextRecord()) 
{
    print 
$db->getField("ResultID").". ".$db->getField("ResultValue")."<br />";
}
?>

Mail Class

I needed a way to send the data from the contact form on this website to myself via email. I created a class that would allow me to send an email in either html or plain text format from my website. The class also validates the email addresses for the sender and recipient as well as the BCC, CC, and Reply-to, if provided.

Source Code:
<?php
/**
 * @brief This class contains the functions used to send an email message.
 * @author Becky Resler <becky@hightechredneckwoman.com>
 * @version 1.0 - 10/13/2008 Original Version.
 * @copyright 2008 Becky Resler http://www.hightechredneckwoman.com
 * 
 * CHANGELOG:
 * version 1.0 - 10/13/2008 Original Version.
 */

class CustomMail
{
    
// set up the public variables for the class.
    
public $errors;
    
// set up the private variables for the class.
    
private $_headers;
    private 
$_boundary;
    
    
/**
     * @brief This function initializes the class.
     */
    
public function __construct()
    {
        
$this->reset();
    }
    
    
/**
     * @brief This function sets the default values for the member variables.
     */
    
public function reset()
    {
        
$this->errors       = array();
        
$this->_headers     = array();
        
$this->_boundary    "custom_mail_boundary";
    }
    
    
/**
     * @brief This function sends an email.
     * @param string - $sender - The email address the email is being sent FROM.
     * @param string - $receiver - The email address the email is being sent TO. Can be multiple as long as they are separated by a comma.
     * @param string - $subject - The subject of the email.
     * @param string - $text_message - The text message for the email.
     * @param string - $html_message - The html message for the email.
     * @param string - $reply_to - The email address replies are to be sent to.
     * @param string - $cc - The email address that copies of the email are to be sent to. Can be multiple as long as they are separated by a comma.
     * @param string - $bcc - The email address that blind copies of the email are to be sent to. Can be multiple as long as they are separated by a comma.
     * @param int - $priority - The priority of the email message. Optional. Defaults to 3. 1: Highest, 5: Lowest.
     * @param string - $bounce_email - The email address that returned messages should be sent to.
     * @return bool - true if sent successfully; otherwise false.
     */
    
public function send($sender$receiver$subject$text_message$html_message$reply_to ""$cc ""$bcc ""$priority 3$bounce_email "")
    {
        
// validate the email addresses
        
if($this->_validate_email_addresses($sender$receiver$reply_to$cc$bcc$bounce_email) !== true)
        {
            
error_log("CustomMail::send() -- Email Validation Issue: ".implode("\n"$this->errors));
            return 
false;
        }
        
        
// if the reply-to is blank, set it to the sender
        
if(empty($reply_to))
            
$reply_to $sender;
        
// if the bounce email is blank, set it to the sender
        
if(empty($bounce_email))
            
$bounce_email $sender;
        
        
// add the headers
        
$this->_add_header("From: {$sender}");
        
$this->_add_header("Return-Path: <{$bounce_email}>");
        
$this->_add_header("Reply-To: {$sender}");
        if(!empty(
$cc))
            
$this->_add_header("Cc: {$cc}");
        if(!empty(
$bcc))
            
$this->_add_header("Bcc: {$bcc}");
        
$this->_add_header("X-Priority: ".intval($priority));
        
$this->_add_header("MIME-Version: 1.0");
        
// setup the boundary
        
$boundary $this->_boundary."_".md5(uniqid(time()));
        
$this->_add_header("Content-Type: multipart/alternative; boundary={$boundary}\n");
        
$this->_add_header("This is a multi-part message in MIME format."); 
        
$this->_add_header("--{$boundary}");
        
// set up the text message
        
$this->_add_header("Content-Type: text/plain; charset=ISO-8859-1");
        
$this->_add_header("Content-Transfer-Encoding: 7bit\n");
        
$this->_add_header($text_message);
        
$this->_add_header("--{$boundary}");
        
// set up the html message
        
$this->_add_header("Content-Type: text/HTML; charset=ISO-8859-1");
        
$this->_add_header("Content-Transfer-Encoding: 7bit\n");
        
$this->_add_header($html_message);
        
$this->_add_header("--{$boundary}--");
        
        
// put together the header string from the array
        
$headers implode("\r\n"$this->_headers);
        
// trim off the trailing \r\n
        
$headers rtrim($headers"\r\n");
        
        
// send the message
        
if(mail($receiver$subject""$headers) !== true)
        {
            
error_log("CustomMail::send() -- Error sending email. Sender = {$sender}, Receiver = {$receiver}, Message = {$html_message}");
            return 
false;
        }
        
        return 
true;
    }
    
    
/**
     * @brief This function validates an email address.
     * @param string - $email_address - The email address to validate.
     * @return bool - true if valid; otherwise false.
     */
    
public function is_valid_email($email_address)
    {
        
// First, we check that there's one @ symbol, and that the lengths are right
        
if(!ereg("^[^@]{1,64}@[^@]{1,255}$"$email_address)) 
        {
            
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
            
return false;
        }
    
        
// Split it into sections to make life easier
        
$email_array explode("@"$email_address);
        
$local_array explode("."$email_array[0]);
        
        for(
$i 0$i sizeof($local_array); $i++) 
        {
            if (!
ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$"$local_array[$i]))
                return 
false;
        }  
    
        
// Check if domain is IP. If not, it should be valid domain name
        
if(!ereg("^\[?[0-9\.]+\]?$"$email_array[1]))
        {
            
$domain_array explode("."$email_array[1]);
            if(
sizeof($domain_array) < 2
                return 
false// Not enough parts to domain
    
            
for($i 0$i sizeof($domain_array); $i++) 
            {
                if(!
ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$"$domain_array[$i]))
                    return 
false;
            }
        }
        
        return 
true;
    }
    
    
/**
     * @brief This function adds an additional header option for the email.
     * @param string - $header - The header option.
     */
    
private function _add_header($header)
    {
        
array_push($this->_headers$header);
    }
    
    
/**
     * @brief This function validates the email addresses for the email message.
     * @param string - $sender - The email address the email is being sent FROM.
     * @param string - $receiver - The email address the email is being sent TO. Can be multiple as long as they are separated by a comma.
     * @param string - $reply_to - The email address replies are to be sent to.
     * @param string - $cc - The email address that copies of the email are to be sent to. Can be multiple as long as they are separated by a comma.
     * @param string - $bcc - The email address that blind copies of the email are to be sent to. Can be multiple as long as they are separated by a comma.
     * @param string - $bounce_email - The email address that returned messages should be sent to.
     * @return bool - true if all email addresses validate; otherwise false.
     */
    
private function _validate_email_addresses($sender$receiver$reply_to$cc$bcc$bounce_email)
    {
        
$is_valid true;
        
        
// sender is required
        
if(empty($sender))
        {
            
array_push($this->errors"'From' email address not provided.");
            
$is_valid false;
        } 
        else
        {
            if(
$this->is_valid_email($sender) !== true)
            {
                
array_push($this->errors"Invalid 'From' email address.");
                
$is_valid false;
            }
        }
        
// receiver is required
        
if(empty($receiver))
        {
            
array_push($this->errors"'To' email address not provided.");
            
$is_valid false;
        } 
        else
        {
            
// there could be multiple addresses, so split into an array and validate individually
            
$invalid_receiver false;
            
$receiver_emails explode(","$receiver);
            foreach(
$receiver_emails as $to_email)
            {
                
$to_email trim($to_email);    // trim off any beginning or trailing whitespace
                
if($this->is_valid_email($to_email) !== true)
                    
$invalid_receiver true;
            }
            
// if there was an invalid value, set up the error
            
if($invalid_receiver === true)
            {
                
array_push($this->errors"Invalid 'To' email address(es).");
                
$is_valid false;
            }
        }
        
// reply-to is optional
        
if(!empty($reply_to))
        {
            if(
$this->is_valid_email($reply_to) !== true)
            {
                
array_push($this->errors"Invalid 'Reply-To' email address.");
                
$is_valid false;
            }
        }
        
// cc is optional
        
if(!empty($cc))
        {
            
// there could be multiple addresses, so split into an array and validate individually
            
$invalid_cc false;
            
$cc_emails explode(","$cc);
            foreach(
$cc_emails as $cc_email)
            {
                
$cc_email trim($cc_email);    // trim off any beginning or trailing whitespace
                
if($this->is_valid_email($cc_email) !== true)
                    
$invalid_cc true;
            }
            
// if there was an invalid value, set up the error
            
if($invalid_cc === true)
            {
                
array_push($this->errors"Invalid 'Cc' email address(es).");
                
$is_valid false;
            }
        }
        
// bcc is optional
        
if(!empty($bcc))
        {
            
// there could be multiple addresses, so split into an array and validate individually
            
$invalid_bcc false;
            
$bcc_emails explode(","$bcc);
            foreach(
$bcc_emails as $bcc_email)
            {
                
$bcc_email trim($bcc_email);    // trim off any beginning or trailing whitespace
                
if($this->is_valid_email($bcc_email) !== true)
                    
$invalid_bcc true;
            }
            
// if there was an invalid value, set up the error
            
if($invalid_bcc === true)
            {
                
array_push($this->errors"Invalid 'Bcc' email address(es).");
                
$is_valid false;
            }
        }
        
// bounce is optional
        
if(!empty($bounce_email))
        {
            if(
$this->is_valid_email($bounce_email) !== true)
            {
                
array_push($this->errors"Invalid 'Return-path' email address.");
                
$is_valid false;
            }
        }
        
        return 
$is_valid;
    }
}
?>
Example:
<?php
require_once "cls_custom_mail.php";

$recipient      "my@email.com";
$sender_email   get_request("sender_email");
$subject        get_request("subject");
$text_message   get_request("text_message");
$html_message   get_request("html_message");

$cmail = new CustomMail();
if(
$cmail->send($sender_email$recipient$subject$text_message$html_message) !== true)
    print 
"There was an error sending the message.  Please try again.";
else 
    print 
"The message was sent successfully.";  
?>

Select Box Manipulation

There are times where I have needed to move options between two select boxes on a form. I had found a javascript class that allowed me to do that, but it seemed overly complex. After delving into the world of jQuery, I put together some code that was MUCH simpler.

Source Code (jQuery):
$(document).ready(function() {
    $("#add").click(function(e){
        $("#leftOptions option:selected").remove().appendTo("#rightOptions");
        e.preventDefault();
    });
    $("#addall").click(function(e){
        $("#leftOptions option").each(function(i){
            $(this).attr("selected", "selected");
            e.preventDefault();
            $("#add").trigger("click", e);
        });
    });
 
    $("#remove").click(function(e){
        $("#rightOptions option:selected").remove().appendTo("#leftOptions");
        e.preventDefault();
    });
    $("#removeall").click(function(e){
        $("#rightOptions option").each(function(i){
            $(this).attr("selected", "selected");
            e.preventDefault();
            $("#remove").trigger("click");
        });
    });
});
Source Code (HTML):
<form name="test" id="test">
<div class="options">
    <select name="leftOptions" id="leftOptions" multiple="multiple" size="5">
        <option value="1">option 1</option>
        <option value="2">option 2</option>
        <option value="3">option 3</option>
        <option value="4">option 4</option>
    </select><br />
    <button id="add">Add &gt;</button><br />
    <button id="addall">Add ALL &gt;</button>   
</div>
<div class="options">
    <select name="rightOptions" id="rightOptions" multiple="multiple" size="5">
        <option value="a">option a</option>
        <option value="b">option b</option>
    </select><br />
    <button id="remove">&lt; Remove</button><br />
    <button id="removeall">&lt; Remove ALL</button>
</div>
</form>
Example:




External Link Indicator

On my websites, I tend to have external links open in new windows. I was using the target="_blank" attribute for links to achieve this. After researching jQuery, I decided that there was a better way to achieve this. That is why I created a snippet of code to do just that.

Source Code (jQuery): Source Code (HTML): Example:

Modal Window (for groups)

When I was putting together this website, I decided that I wanted to put the details for my portfolio into a modal or lightbox window. There are lots of jQuery plugins that do this. I also wanted to be able to page through the various sites in my portfolio without having to close the lightbox and select the next site. I wasn't able to find a plugin that would allow me to do that. All of the plugins that paged through sets were only for images. So I decided to create my own plugin. The plugin will open a modal/lightbox window and display the contents of the link, obtained via ajax, and the modal/lightbox will have navigation options to page through all of the items within the same group (specified by the rel="" attribute on the link. Please see my portfolio page for an example of this plugin.

Source Code (jQuery plugin): Source Code (jQuery): Source Code (HTML):

Toggle

There have been numerous times where I have wanted to be able to show and/or hide a section on a page, or both. I had a javascript function that I was using to set the css display value to accomplish this. After working with jQuery, I decided to put together a plugin that would toggle sections for me.

Source Code (jQuery plugin):
/*
 * jQuery toggleIt plugin
 *
 * version 0.1 (02/17/2009)
 * Copyright (c) 2009 Becky Resler
 * 
 * @description Add the ability to toggle (show/hide) an element.
 * 
 * For more details see: 
 * For a full demo see:  
 * 
 * @example $("#toggleme").toggleIt();
 * @desc    Provide a link/button to toggle the element.
 * 
 * @option String defaultState (optional)   A string indicating if the element should be opened or closed on page load.
 *                                          Default value: "open"
 * 
 * @option String animationSpeed (optional) A string indicating the animation speed. OPTIONS: slow | normal | fast | # of milliseconds | blank
 *                                          Default value: ""
 * 
 * @option String toggleLocation (optional) A string indication where the toggle action item should be placed, either before or after the element to be toggled.
 *                                          Default value: "before"
 * 
 * @option String toggleType (optional)     A string indicating what the toggle action item should be, either link or button. 
 *                                          Default value: "link"
 * 
 * @option String textShow (optional)       A string indicating what text should be displayed to indicate that the element can be shown.
 *                                          Default value: "Show"
 * 
 * @option String textHide (optional)       A string indicating what text should be displayed to indicate that the element can be hidden. 
 *                                          Default value: "Hide"
 * 
 * @option Array toggleWrapper (optional)   An array containing the html to wrap the element in.
 *                                          Default value: { before: '<div style="margin-top: 4px; margin-bottom: 4px;">', after: '</div>' }
 * 
 * @option Array animationType (optional)   An array containing the animation to be used to show and hide the element. OPTIONS (show): show | slideDown | fadeIn || OPTIONS (hide): hide | slideUp | fadeOut
 *                                          Default value: { show: "show", hide: "hide" }
 * 
 * @name toggleIt
 * @type jQuery
 * @cat Plugins/toggleIt
 * @return jQuery 
 * @author Becky Resler (hightechredneckwoman@gmail.com)
 */
jQuery.fn.toggleIt = function(opt) {
    // set up the default options for the plugin
    var defaults = {
        defaultState:   "open",     // OPTIONS: open | closed
        animationSpeed: "",         // OPTIONS: slow | normal | fast | # of milliseconds | blank
        toggleLocation: "before",   // OPTIONS: before | after
        toggleType:     "link",     // OPTIONS: link | button
        textShow:       "Show",
        textHide:       "Hide",
        toggleWrapper:  { before: '<div style="margin-top: 4px; margin-bottom: 4px;">', after: '</div>' },
        animationType:  { 
                            show: "show",   // OPTIONS: show | slideDown | fadeIn 
                            hide: "hide"    // OPTIONS: hide | slideUp | fadeOut
                        }
    };
 
    // extend the default options for this plugin
    options = jQuery.extend(defaults, opt);
 
    // iterate through things
    return this.each(function(){
        var $targetElement  = $(this);
        var targetElementID = $targetElement.attr("id");
        var toggleElementID = targetElementID + "toggle";
        var textShow        = options.textShow;
        var textHide        = options.textHide;
        var animationShow   = options.animationType.show;
        var animationHide   = options.animationType.hide;
 
        /*** initialize things for the defaultState ***/
        // set up the toggle link/button
        if(options.toggleType == "button")
            var elementHTML = (options.defaultState == "open") ? '<button id="'+toggleElementID+'">'+textHide+'</button>' : '<button id="'+toggleElementID+'">'+textShow+'</button>';
        else
            var elementHTML = (options.defaultState == "open") ? '<a href="#" id="'+toggleElementID+'">'+textHide+'</a>' : '<a href="#" id="'+toggleElementID+'">'+textShow+'</a>';
 
        // put the wrapper around the button/link html
        var toggleHTML = options.toggleWrapper.before + elementHTML + options.toggleWrapper.after;
 
        // add the toggle link
        if(options.toggleLocation == "before")
            $targetElement.before(toggleHTML);
        else
            $targetElement.after(toggleHTML);
 
        // if defaultState is closed, then hide the element
        if(options.defaultState != "open")
            $targetElement.hide();
 
        /*** bind the toggle action ***/
        // need to take into account the defaultState when setting up the toggle action so get the first one right
        if(options.defaultState == "open")
        {
            $("#"+toggleElementID).toggle(function(){
                hideElement($(this), $targetElement, textShow, animationHide);
                return false;            
            }, function(){
                showElement($(this), $targetElement, textHide, animationShow);
                return false;
            });
        }
        else
        {
            $("#"+toggleElementID).toggle(function(){
                showElement($(this), $targetElement, textHide, animationShow);
                return false;            
            }, function(){
                hideElement($(this), $targetElement, textShow, animationHide);
                return false;
            });
        }
    });
 
 
    // this function will show the target element
    function showElement($toggleElement, $targetElement, newText, animationType)
    {
        $targetElement[animationType](options.animationSpeed);
        $toggleElement.html(newText);
        $toggleElement.blur();  // get rid of the outline on the link/button
    }
 
    // this function will hide the target element
    function hideElement($toggleElement, $targetElement, newText, animationType)
    {
        $targetElement[animationType](options.animationSpeed);
        $toggleElement.html(newText);
        $toggleElement.blur();  // get rid of the outline on the link/button
    }
};
Source Code (jQuery):
$(document).ready(function(){
    // using default options
    $("#section1").toggleIt();
 
    // with default options overridden
    $("#section2").toggleIt({
        defaultState:   "closed",
        toggleType:     "button",
        textShow:       "view section",
        textHide:       "HIDE section",
        animationType:  { show: "slideDown", hide: "slideUp" }
    });
});
Source Code (HTML):
<div id="section1">
    Here is the content of the section that will be toggled.<br /><br />
    This section will use all of the default options.<br /><br />
    It will be open initially and can be toggled closed by a link.
</div>
 
<div id="section2">
    Here is the content of another section that will be toggled.<br /><br />
    This section has options specifically set for it.<br /><br />
    It will be closed initially and can be toggled open by a button.
</div>
Example:
Here is the content of the section that will be toggled.

This section will use all of the default options.

It will be open initially and can be toggled closed by a link.
Here is the content of another section that will be toggled.

This section has options specifically set for it.

It will be closed initially and can be toggled open by a button.