Function: format_name

Posted on Oct 15, 2006 in Code, PHP | 0 comments

This is a rather custom little function, but still may prove of use. It’s a PHP function that properly capitalizes a name (first and last), and ensures the other characters are lowercased. I have a vague memory of basing this on someone else’s code… but it’s long since gone from my mind.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*--------------------------------------------------------------------------*\
  Function:    format_name
  Purpose:     takes a name as a parameter and attempts to correctly format
               it for upper- and lower-case.
\*--------------------------------------------------------------------------*/

function format_name($name)
{
  $name = strtolower(stripslashes($name));

  // uppercase any multi-barrelled names
  $names_array = explode('-', $name);

  for ($i=0; $i<count($names_array); $i++)
  {  
    // for names like McDonald or O'Connor
    if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]', $names_array[$i]))
      $names_array[$i][2] = strtoupper($names_array[$i][2]);

    // always set the first letter to uppercase, no matter what
    $names_array[$i] = ucfirst($names_array[$i]);
  }

  // Piece the names back together
  $name = implode('-',$names_array);

  // return upper-casing on all missed (but required) elements
  return ucwords($name);
}
Read More

States & Provinces dropdown

Posted on Oct 15, 2006 in Code, PHP | 2 comments

I can’t count the number of times I’ve had to create this from scratch. And every time I feel like a real bonehead for having to recreate it. So here it is for easy reference. I left in the PHP code for re-populating the field. If you don’t need it, it’s just search-and-replace away.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    <select name="mailing_state">
      <option value="">Please Select</option>
      <optgroup label="Provinces">
        <option value="AB" <?php if ($page["mailing_state"] == "AB") echo "selected"; ?>>Alberta</option>
        <option value="BC" <?php if ($page["mailing_state"] == "BC") echo "selected"; ?>>British Columbia</option>
        <option value="MB" <?php if ($page["mailing_state"] == "MB") echo "selected"; ?>>Manitoba</option>
        <option value="NB" <?php if ($page["mailing_state"] == "NB") echo "selected"; ?>>New Brunswick</option>
        <option value="NL" <?php if ($page["mailing_state"] == "NL") echo "selected"; ?>>Newfoundland & Labrador</option>
        <option value="NT" <?php if ($page["mailing_state"] == "NT") echo "selected"; ?>>Northwest Territories</option>
        <option value="NS" <?php if ($page["mailing_state"] == "NS") echo "selected"; ?>>Nova Scotia</option>
        <option value="NU" <?php if ($page["mailing_state"] == "NU") echo "selected"; ?>>Nunavut</option>
        <option value="ON" <?php if ($page["mailing_state"] == "ON") echo "selected"; ?>>Ontario</option>
        <option value="PE" <?php if ($page["mailing_state"] == "PE") echo "selected"; ?>>Prince Edward Island</option>
        <option value="QC" <?php if ($page["mailing_state"] == "QC") echo "selected"; ?>>Quebec</option>
        <option value="SK" <?php if ($page["mailing_state"] == "SK") echo "selected"; ?>>Saskatchewan</option>
        <option value="YT" <?php if ($page["mailing_state"] == "YT") echo "selected"; ?>>Yukon</option>
      </optgroup>
      <optgroup label="States">
        <option value="AL" <?php if ($page["mailing_state"] == "AL") echo "selected"; ?>>Alabama</option>
        <option value="AK" <?php if ($page["mailing_state"] == "AK") echo "selected"; ?>>Alaska</option>
        <option value="AZ" <?php if ($page["mailing_state"] == "AZ") echo "selected"; ?>>Arizona</option>
        <option value="AR" <?php if ($page["mailing_state"] == "AR") echo "selected"; ?>>Arkansas</option>
        <option value="CA" <?php if ($page["mailing_state"] == "CA") echo "selected"; ?>>California</option>
        <option value="CO" <?php if ($page["mailing_state"] == "CO") echo "selected"; ?>>Colorado</option>
        <option value="CT" <?php if ($page["mailing_state"] == "CT") echo "selected"; ?>>Connecticut</option>
        <option value="DE" <?php if ($page["mailing_state"] == "DE") echo "selected"; ?>>Delaware</option>
        <option value="DC" <?php if ($page["mailing_state"] == "DC") echo "selected"; ?>>District of Columbia</option>
        <option value="FL" <?php if ($page["mailing_state"] == "FL") echo "selected"; ?>>Florida</option>
        <option value="GA" <?php if ($page["mailing_state"] == "GA") echo "selected"; ?>>Georgia</option>
        <option value="HI" <?php if ($page["mailing_state"] == "HI") echo "selected"; ?>>Hawaii</option>
        <option value="ID" <?php if ($page["mailing_state"] == "ID") echo "selected"; ?>>Idaho</option>
        <option value="IN" <?php if ($page["mailing_state"] == "IN") echo "selected"; ?>>Illinois</option>
        <option value="IL" <?php if ($page["mailing_state"] == "IL") echo "selected"; ?>>Indiana</option>
        <option value="IA" <?php if ($page["mailing_state"] == "IA") echo "selected"; ?>>Iowa</option>
        <option value="KS" <?php if ($page["mailing_state"] == "KS") echo "selected"; ?>>Kansas</option>
        <option value="KY" <?php if ($page["mailing_state"] == "KY") echo "selected"; ?>>Kentucky</option>
        <option value="LA" <?php if ($page["mailing_state"] == "LA") echo "selected"; ?>>Louisiana</option>
        <option value="ME" <?php if ($page["mailing_state"] == "ME") echo "selected"; ?>>Maine</option>
        <option value="MD" <?php if ($page["mailing_state"] == "MD") echo "selected"; ?>>Maryland</option>
        <option value="MA" <?php if ($page["mailing_state"] == "MA") echo "selected"; ?>>Massachusetts</option>
        <option value="MI" <?php if ($page["mailing_state"] == "MI") echo "selected"; ?>>Michigan</option>
        <option value="MN" <?php if ($page["mailing_state"] == "MN") echo "selected"; ?>>Minnesota</option>
        <option value="MS" <?php if ($page["mailing_state"] == "MS") echo "selected"; ?>>Mississippi</option>
        <option value="MO" <?php if ($page["mailing_state"] == "MO") echo "selected"; ?>>Missouri</option>
        <option value="MT" <?php if ($page["mailing_state"] == "MT") echo "selected"; ?>>Montana</option>
        <option value="NE" <?php if ($page["mailing_state"] == "NE") echo "selected"; ?>>Nebraska</option>
        <option value="NV" <?php if ($page["mailing_state"] == "NV") echo "selected"; ?>>Nevada</option>
        <option value="NH" <?php if ($page["mailing_state"] == "NH") echo "selected"; ?>>New Hampshire</option>
        <option value="NJ" <?php if ($page["mailing_state"] == "NJ") echo "selected"; ?>>New Jersey</option>
        <option value="NM" <?php if ($page["mailing_state"] == "NM") echo "selected"; ?>>New Mexico</option>
        <option value="NY" <?php if ($page["mailing_state"] == "NY") echo "selected"; ?>>New York</option>
        <option value="NC" <?php if ($page["mailing_state"] == "NC") echo "selected"; ?>>North Carolina</option>
        <option value="ND" <?php if ($page["mailing_state"] == "ND") echo "selected"; ?>>North Dakota</option>
        <option value="OH" <?php if ($page["mailing_state"] == "OH") echo "selected"; ?>>Ohio</option>
        <option value="OK" <?php if ($page["mailing_state"] == "OK") echo "selected"; ?>>Oklahoma</option>
        <option value="OR" <?php if ($page["mailing_state"] == "OR") echo "selected"; ?>>Oregon</option>
        <option value="PA" <?php if ($page["mailing_state"] == "PA") echo "selected"; ?>>Pennsylvania</option>
        <option value="RI" <?php if ($page["mailing_state"] == "RI") echo "selected"; ?>>Rhode Island</option>
        <option value="SC" <?php if ($page["mailing_state"] == "SC") echo "selected"; ?>>South Carolina</option>
        <option value="SD" <?php if ($page["mailing_state"] == "SD") echo "selected"; ?>>South Dakota</option>
        <option value="TN" <?php if ($page["mailing_state"] == "TN") echo "selected"; ?>>Tennessee</option>
        <option value="TX" <?php if ($page["mailing_state"] == "TX") echo "selected"; ?>>Texas</option>
        <option value="UT" <?php if ($page["mailing_state"] == "UT") echo "selected"; ?>>Utah</option>
        <option value="VT" <?php if ($page["mailing_state"] == "VT") echo "selected"; ?>>Vermont</option>
        <option value="VA" <?php if ($page["mailing_state"] == "VA") echo "selected"; ?>>Virginia</option>
        <option value="WA" <?php if ($page["mailing_state"] == "WA") echo "selected"; ?>>Washington</option>
        <option value="WV" <?php if ($page["mailing_state"] == "WV") echo "selected"; ?>>West Virginia</option>
        <option value="WI" <?php if ($page["mailing_state"] == "WI") echo "selected"; ?>>Wisconsin</option>
        <option value="WY" <?php if ($page["mailing_state"] == "WY") echo "selected"; ?>>Wyoming</option>
      </optgroup>
    </select>
Read More

Function: check_duplicate_filename()

Posted on Sep 12, 2006 in Code, PHP | 0 comments

This little helper function is part of Form Tools, but it’s so handy I thought I’d draw attention to it by placing it in it’s own post. In the next short while I’ll be improving the UI on this site to list code functions for quick access. This post (and other code posts) is in anticipation of that. Read the blurb below for a description of how the function works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*------------------------------------------------------------------------------------------------*\
  Function:    check_duplicate_filename
  Description: examines a folder for a particular filename. If it finds it, it renames the filename
               to x_$filename, where x is an integer starting at 1. Then it checks to see if that
               file exists, also. Repeats until it finds a filename that isn't in use, and returns
               that value.
  Assumption:  folder exists and is readable.
  Parameters:  $folder   - the folder to examine
               $filename - the name of the filename to check for
  Returns:     the name of the filename
\*------------------------------------------------------------------------------------------------*/

function check_duplicate_filename($folder, $filename)
{
  // check the supplied dir is a valid, readable directory
  if (!is_dir($folder) && is_readable($folder))
    return;

  // the filename string to return
  $return_filename = $filename;

  // store all the filenames in the folder into an array  
  $filenames = array();
  if ($handle = opendir($folder))
  {
    while (false !== ($file = readdir($handle)))
      $filenames[] = $file;
  }

  // if a file with the same name exists in the directory, find the next free filename of the form:
  // x_$filename, where x is a number starting with 1
  if (in_array($filename, $filenames))
  {
    // if it already starts with x_, strip off the prefix.
    if (preg_match("/^\d+_/", $filename))
      $filename = preg_replace("/^\d+_/", "", $filename);

    // now find the next available filename
    $next_num = 1;
    $return_filename = $next_num . "_" . $filename;
    while (in_array($return_filename, $filenames))
    {
      $return_filename = $next_num . "_" . $filename;
      $next_num++;
    }
  }

  // return the appropriate filename
  return $return_filename;
}
Read More

Function: html_dump()

Posted on Aug 29, 2006 in Code, PHP | 0 comments

This function isn’t completed, but I’ll add it here anyway. One of the primary reasons I’m using WordPress to store my code is to facilitate tracking it down later. I’ll return to this and polish it off at some point. Or someone else out there could do it for me…!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*----------------------------------------------------------------------------*\
  Function:   html_dump
  Abstract:   development helper tool to output PHP variables in HTML-friendly
                  formats. [written to emulate ColdFusion's <cfdump> tag.]
  Parameters: - $hash: the hash to display (e.g. $_POST)
                   - $label: a label for the outputted text.
                   - $hidden_onload: hides the displayed object by default
  Returns:    a string containing an HTML-rendering of the input variable.
 
  INCOMPLETE.
\*----------------------------------------------------------------------------*/

function html_dump($var, $label = "", $start_hidden = false)
{
  // embedded function which determines if an array is a hash or not.
  function is_hash($var)
  {
    if (!is_array($var))
      return false;
 
    return array_keys($var) !== range(0,sizeof($var)-1);
  }

 
  $table_id = rand();         // create a unique ID for the displayed table
  $var_type = gettype($var);  // determine what kind of variable we're displaying
  $html     = "";             // stores the HTML-ified variable


  // determine hide/show javascript enabling user to toggle visibility of
  // outputted variable contents.
  $js_hide = 'document.getElementById("html_dump_' . $table_id . '_show").style.display = "none";
              document.getElementById("html_dump_'
. $table_id . '_hide").style.display = "block";';
  $js_show = 'document.getElementById("html_dump_' . $table_id . '_show").style.display = "block";
              document.getElementById("html_dump_'
. $table_id . '_hide").style.display = "none";';


  // determine the CSS display attribute of the hidden & visible tables
  $start_hidden_cs = ($start_hidden) ? "" : "display: none";
  $start_show_cs   = ($start_hidden) ? "display: none" : "";
 
             
  switch ($var_type)
  {
    case "array":

       // ------------------------------- HASH ----------------------------
       if (is_hash($var))
       {
         // styles for hash display
         $table_style  = "width: 100px; background-color: #efefef;";
         $label_style  = "background-color: #003300; font-family: arial; font-size: 8pt; color: white; font-weight: bold;";
         $key_style    = "background-color: #339933; color: white; font-family: arial; font-size: 8pt;";
         $value_style  = "background-color: white; color: black; font-family: arial; font-size: 8pt;";
         $button_style = "font-family: arial; font-size: 7pt;";

         // HIDDEN table
         $html .= "<table id='html_dump_{$table_id}_hide' cellpadding='1' cellspacing='1' style='$table_style; $start_hidden_cs;'>
               <tr>
                 <td style='$label_style' nowrap>[ Hash ] $label</td>
                 <td style='$label_style'>                
                   <input type='button' value='SHOW' style='$button_style' onclick='$js_show' />
                 </td>
               </tr>
               </table>"
;

         // VISIBLE table
         $html .= "
             <table id='html_dump_{$table_id}_show' cellpadding='1' cellspacing='1' style='$table_style; $start_show_cs;'>
             <tr>
               <td style='$label_style' nowrap>[ Hash ] $label</td>
               <td style='$label_style'>
                 <input type='button' value='HIDE' style='$button_style' onclick='$js_hide' />              
               </td>
             </tr>"
;

         foreach ($var as $key=>$val)
         {
           $html .= "<tr>
                   <td style='$key_style'>$key</td>
                   <td style='$value_style'>$val</td>
                 </tr>"
;
         }
         $html .= "</table>";
       }

       // ------------------------------- ARRAY ----------------------------
       else
       {
         $html .= "Array";
       }
       
       break;
  }
  return $html;
}
Read More

Function: trim_long_string()

Posted on Aug 29, 2006 in Code, PHP | 0 comments

The name of this function makes it pretty self-explanatory. One particularly useful thing about the function is that it allows you to either trim it at the end and add an ellipsis (…) or insert HTML page breaks (<br />). Very useful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*------------------------------------------------------------------------------------------------*\
  Function:    trim_long_string
  Description: helper function to help manage long strings. This function either adds an ellipsis
                   or inserts a <br /> at the position specified, and returns the result.  
  Parameters: $str    - the string to examine
                   $length - the max length of the string / place to insert <br />
                   $flag   - "ellipsis" / "page_break"
\*------------------------------------------------------------------------------------------------*/

function trim_long_string($str, $length, $flag = "ellipsis")
{
  $new_string = "";
  if (strlen($str) < $length)
    $new_string = $str;
  else
  {
    if ($flag == "ellipsis")
      $new_string = substr($str, 0, $length) . "...";
    else
    {
      $parts = str_split($str, $length);
      $new_string = join("<br />", $parts);
    }
  }

  return $new_string;
}
Read More

Sending HTML + text emails in PHP

Posted on Aug 16, 2006 in Code, PHP | 0 comments

I got this sucker working for Form Tools last month after working my butt off making sense of the many idiosyncracies of the many servers out there. Well, turns out I missed a problem. After half a dozen people complained I bumped this up on my priorities and investigated it.

If you need to ever send HTML+text emails in PHP, I’d thoroughly recommend the following article: http://www.zend.com/zend/trick/html-email.php

But be careful not to deviate from the example code without fully understanding it! Every last aspect of the code is there for a purpose, including the occasional double endlines. Unfortunately, the writer doesn’t delve into the details in any great depth so one is apt to assume they’re not important. One thing that’s not covered is determining an endline based on OS type. Here’s my tweaked version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// determine the end of line character (based on OS)
$eol = "\n";
if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
$eol = "\r\n";
else if (strtoupper(substr(PHP_OS, 0, 3) == 'MAC'))
$eol = "\r";

// add From: header
$headers = "From: webserver@localhost$eol";

//specify MIME version 1.0
$headers .= "MIME-Version: 1.0$eol";

// unique boundary
$boundary = uniqid("HTMLDEMO");

// tell e-mail client this e-mail contains alternate versions
$headers .= "Content-Type: multipart/alternative" .
"; boundary = $boundary$eol$eol";

// message to people with clients who don't understand MIME
$headers .= "This is a MIME encoded message.$eol";

// plain text version of message
$headers .= "--$boundary$eol" .
"Content-Type: text/plain; charset=ISO-8859-1$eol" .
"Content-Transfer-Encoding: base64$eol$eol";
$headers .= chunk_split(base64_encode("This is the plain text version!"));

// HTML version of message
$headers .= "--$boundary\r\n" .
"Content-Type: text/html; charset=ISO-8859-1$eol" .
"Content-Transfer-Encoding: base64$eol$eol";
$headers .= chunk_split(base64_encode("This the <strong>HTML</strong> version!"));

// send message
mail("root@localhost", "An HTML Message", "", $headers);

I can vouch for the code working on Windows and Unix servers. Good luck…!

Read More