NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Web Hosting

best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< September, 2010 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
2627282930
Search Blog

Recent Comments
Re: Using Google as your CF Mail Server (by Mike at 9/07 4:02 PM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Nithin Chacko Ninan at 9/07 1:34 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Nithin Chacko Ninan at 9/07 1:33 AM)
Re: Configuring Apache To Use Multiple Versions of ColdFusion (by Lola LB at 9/06 6:28 AM)
Re: Configuring Apache To Use Multiple Versions of ColdFusion (by ComboFusion at 9/06 5:17 AM)
Re: Railo 3.1 on Windows Server 2008 and IIS7 - Part 3 of 3 (by Jon at 8/27 2:04 PM)
Re: Hosts File Changes Not Acknowledged on Vista 64 (by Spacy at 8/24 3:46 PM)
Re: THE DAY CFUNITED DIED (by ComboFusion at 8/23 10:50 AM)
Re: My Grandpa (by Tasha at 8/10 4:29 PM)
Re: Just What IS a 'Service Layer', Anyway? (by dougboude at 8/02 10:10 AM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

13 July 2010
PHP vs COLDFUSION
a brief, biased comparison

I had the privilege of doing a short presentation at our local CFUG meeting last night, the topic being "Coldfusion Vs PHP", so thought I'd share the slides and some brief commentary on some of them. We didn't record the meeting, so what you're about to see is an abbreviated version.

Posted by dougboude at 12:43 PM | PRINT THIS POST! | Link | 9 comments



11 September 2009
501 Error When Sending Mail via Smartermail 6

After several hours of hair pulling, I finally rectified an issue sending mail via Smartermail 6.0 using PHP's "mail" function. The exact same (crappy) code worked fine on the old freeBSD box, running PHP 4.9 and Apache. But when I migrated the same code to Windows 2008 running IIS7, PHP 4.9 (just to save me potential hassle with upgrading to 5.x), and Smartermail 6.0, I would get delivery log entries like this:

 

13:48:47 [60090] Delivery started for < at 1:48:47 PM
13:48:47 [60091] Delivery started for < at 1:48:47 PM
13:48:50 [60091] Skipping spam checks: No local recipients
13:48:50 [60090] Skipping spam checks: No local recipients
13:48:53 [60091] Sending remote mail for <
13:48:53 [60091] Connecting to 72.9.148.220
13:48:53 [60090] Sending remote mail for <
13:48:53 [60091] Connection to 72.9.148.220 from 69.24.65.218:55153 succeeded
13:48:53 [60091] RSP: 220-secure.extentions.net ESMTP Exim 4.69 #1 Fri, 11 Sep 2009 14:48:51 -0500
13:48:53 [60091] RSP: 220-We do not authorize the use of this system to transport unsolicited,
13:48:53 [60091] RSP: 220 and/or bulk e-mail.
13:48:53 [60091] CMD: EHLO maso165.gearhost.us.com
13:48:53 [60091] RSP: 250-secure.extentions.net Hello maso165.gearhost.us.com [69.24.65.218]
13:48:53 [60091] RSP: 250-SIZE 52428800
13:48:53 [60091] RSP: 250-PIPELINING
13:48:53 [60091] RSP: 250-AUTH PLAIN LOGIN
13:48:53 [60091] RSP: 250-STARTTLS
13:48:53 [60091] RSP: 250 HELP
13:48:53 [60091] CMD: MAIL FROM:<<> SIZE=899
13:48:53 [60091] RSP: 501 <<>: missing or malformed local part
13:48:53 [60091] CMD: QUIT

 

Googling turned up lots of Ruby dudes and dudettes who were encountering the same error trying to send mail via SMTP in Ruby, only since they were using a Ruby class to do it, the true cause of the problem was out of their reach. In a nutshell, the error is generated by a malformed "FROM" address. After trying all manner of experimentation, I finally rectified the issue by removing the space between the colon and the header variables. Here's the original code that created the mail headers, and broke my send attempt:

   

$headers = "From: $MailFrom\r\n";
    $headers .= "Return-path: $MailFrom\r\n";
    $headers .= "Errors-to: $MailFrom\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-7\r\n";
    $headers .= "X-Sender: $MailFrom\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-MSMail-Priority: Normal\r\n";
    $headers .= "X-Mailer: PHP ".phpversion()."\r\n";

 

Here's what the working version of that snippet looks like:

   

$headers = "From:$MailFrom\r\n";
    $headers .= "Return-path:$MailFrom\r\n";
    $headers .= "Errors-to:$MailFrom\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-7\r\n";
    $headers .= "X-Sender:$MailFrom\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-MSMail-Priority: Normal\r\n";
    $headers .= "X-Mailer: PHP ".phpversion()."\r\n";

 

 
So, if you are encountering a 501 error, check your code to ensure that you don't have any extra characters or spaces in your values, such as square brackets, extra opening or closing pointy brackets (< >), and the like.


Just for entertainment purposes and to give you something to wag your head at, let me show you the complete code my predecessor wrote to generate the email headers and values:

$BCCx = 0;
$Ectr = 0;
$BCCx = "";
$MastStr = " ";

               while($Row=mysql_fetch_array($Result)) {

 

                 $Bemail = $Row[EMail];
    if (strpos($Bemail,"@")>0) {
               $BCCctr = $BCCctr + 1;
               $Ectr = $Ectr + 1;
                 if ( strpos($Bemail,";")> 0) {
                     $xx = strpos($Bemail,";");
                     $Bemail = substr($Bemail,0,$xx) . "," . substr($Bemail,$xx+1);
                 }
$dbug = $dbug . "$Row[LastName], $Row[FirstName]&nbsp;&nbsp;&nbsp;";
                     $BCCx = $BCCx . ", " . $Bemail;
                     $MastStr .= "<br><br>" . $Row[EMail] . " .. " . trim($Row[LastName]) . ", " . trim($Row[FirstName]) . " .... d:" . $Row[daytimephone] . " .. n:" . $Row[eveningphone] . " .. cell:" . $Row[cellphone];
     }

               if ($BCCctr == 150) {
                   $BCCctr = 0;

                     $MailJay = "$Row[EMail]";
                     $Subject = $_POST['SubjectLine'];
                     $Strx =    $_POST['MessageLine'];
                     $MailFrom  = $ReplyEmailx;

                  print("<br>mail command done S:$Subject*B:$Strx*<br>");

if ( strpos($MailJay,";")> 0) {
    $xx = strpos($MailJay,";");
    $MailJay = substr($MailJay,0,$xx) . "," . substr($MailJay,$xx+1);
}


    $MailJay = "administrator@somedomain.com"; // new Aug 2004


    $headers = "From:$MailFrom\r\n";


    $headers .= "Return-path: $MailFrom\r\n";
    $headers .= "Errors-to: $MailFrom\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-7\r\n";
    $headers .= "X-Sender: $MailFrom\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-MSMail-Priority: Normal\r\n";
    $headers .= "X-Mailer: PHP ".phpversion()."\r\n";


    $headers .= "BCC:$BCCx\r\n\r\n";

    $Mheaders = $Mheaders . "<br>" . $headers;
    $BCCx = "";


    while (strpos($Subject,"'")>0) { $xx = strpos($Subject,"'");
        $Subject = substr($Subject,0,$xx) . substr($Subject,$xx+1);
    }
    while (strpos($Subject,'"')>0) { $xx = strpos($Subject,'"');
        $Subject = substr($Subject,0,$xx) . substr($Subject,$xx+1);
    }
    while (strpos($Strx,"'")>0) { $xx = strpos($Strx,"'");
        $Strx = substr($Strx,0,$xx) . substr($Strx,$xx+1);
    }
    while (strpos($Strx,'"')>0) { $xx = strpos($Strx,'"');
        $Strx = substr($Strx,0,$xx) . substr($Strx,$xx+1);
    }


// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 mail($MailJay, $Subject, $Strx, $headers, "-f $MailFrom");

Posted by dougboude at 4:00 PM | PRINT THIS POST! | Link | 0 comments
28 August 2009
Locating Files Containing Specified Text in "*IX" Environment

This is nothing revolutionary, but since it was new to me and it DID take me far longer finding the solution via Googling than it should have, I'm posting it here for my own and others' reference.

Let's say you need to do some search and replace of a specified email address within a BUTT LOAD of PHP files you inherited from your predecessor, but you don't want to have to download the whole can of worms via FTP, only the relevant files (I know, I know: why did my predecessor hard code the email address all over the place?). Anyway, this next snippet will give you back a list of all PHP files containing the text specified:


find . -name "*.php" -exec grep -H "someEmailAddress@oldDomain.com" {} \;

 

The results will look something like this:

./data/QuickupAdj.php:                     // $MailStaff = "someEmailAddress@oldDomain.com ";
./data/QuickupAdj.php:                     mail("
someEmailAddress@oldDomain.com ", $Subject, $Strx, $headers, "-f $MailFrom");
./data/QuickupAdj.php:                     // $MailStaff = "
someEmailAddress@oldDomain.com ";
./data/QuickupAdj.php:                   mail("
someEmailAddress@oldDomain.com ", $Subject, $Strx, $headers, "-f $MailFrom");
./data/QuickupAdjo5.php:                     // $MailStaff = "
someEmailAddress@oldDomain.com ";
./data/QuickupAdjo5.php:                     mail("
someEmailAddress@oldDomain.com ", $Subject, $Strx, $headers, "-f $MailFrom");
./data/QuickupAdjo5.php:                     // $MailStaff = "
someEmailAddress@oldDomain.com ";
./data/QuickupAdjo5.php:                   mail("
someEmailAddress@oldDomain.com ", $Subject, $Strx, $headers, "-f $MailFrom");

 

Told ya, nothing special about this post! :)

Doug out.

Posted by dougboude at 8:47 AM | PRINT THIS POST! | Link | 0 comments
30 June 2009
PHP Export to Excel Snippet

For those PHPers out there who are doing an export to Excel, I thought I'd share the solution I came up with. I realize there are already a gabillion examples out there, but I merged some of the better approaches from a few of them that made it fairly elegant, I think (such as leveraging the implode, array_keys, and array_values functions).

Without further adieux...

<?php
//your code here to create your sql statement...we'll call it $finalSQL
 
//go get the data we need...
$Result=mysql_db_query($DBName,$finalSQL,$Link);
//fetching each row as an array and placing it into a holder array ($aData)
while($row = mysql_fetch_assoc($Result)){
 $aData[] = $row;
}
//feed the final array to our formatting function...
$contents = getExcelData($aData);

$filename = "myExcelFile.xls";

//prepare to give the user a Save/Open dialog...
header ("Content-type: application/octet-stream");
header ("Content-Disposition: attachment; filename=".$filename);

//setting the cache expiration to 30 seconds ahead of current time. an IE 8 issue when opening the data directly in the browser without first saving it to a file
$expiredate = time() + 30;
$expireheader = "Expires: ".gmdate("D, d M Y G:i:s",$expiredate)." GMT";
header ($expireheader);

//output the contents
echo $contents;
exit;
?>

<?php
 function getExcelData($data){
    $retval = "";
    if (is_array($data)  && !empty($data))
    {
     $row = 0;
     foreach(array_values($data) as $_data){
      if (is_array($_data) && !empty($_data))
      {
          if ($row == 0)
          {
              // write the column headers
              $retval = implode("\t",array_keys($_data));
              $retval .= "\n";
          }
           //create a line of values for this row...
              $retval .= implode("\t",array_values($_data));
              $retval .= "\n";
              //increment the row so we don't create headers all over again
              $row++;
       }
     }
    }
  return $retval;
 }
?>

 

 

Posted by dougboude at 1:06 PM | PRINT THIS POST! | Link | 5 comments
21 May 2009
Create Dynamic WHERE Clauses in PHP

At times it is necessary to dynamically create delimited lists of items, such as in the WHERE clause of SQL queries. For instance, perhaps our query could have from one to N different OR statements in the WHERE clause based on selections a user makes on a search form, something like

"select userid, firstname, lastname from usertable

WHERE (rank >700 AND rank <1000) OR (rank >200 AND rank < 400) OR (lastname LIKE 'ar%') OR ...."

Looping over items and knowing when to insert a delimiter and when not to takes some extra coding, because you have to track if this is the first or last item in the list or array. Instead of worrying about tracking first or last items, what I do is simply insert the items I need to delimit into an array, and then dump them all out to a properly delimited statement by leveraging the 'implode' function.

Here's a snippet of code I use to create a dynamic WHERE clause for a sql query based on filter criteria submitted via a form. In this example, I am processing a submitted filter criteria named 'rankfilter' to build the WHERE clause for my query:

$Query = "SELECT userid,firstname,lastname,username,password FROM UserTable WHERE (";//start my query string...
$aRanks = split(",",$_GET['rankfilter']);//turn the submitted list of rank options into an array...
$aORs = array();//create an empty array to hold the individual criteria to be OR'd...
foreach($aRanks as $thisrank){
 switch($thisrank){
  case "core":
   array_push($aORs,'(rank >=700 AND rank <100000)');
   break;
  case "all":
   array_push($aORs,'(rank >=0 AND rank <100000)');
   break;
  case "1":
   array_push($aORs,'(rank >=500 AND rank <700)');
   break; 
  case "2":
   array_push($aORs,'(rank >=400 AND rank <500)');
   break; 
  case "3":
   array_push($aORs,'(rank >=300 AND rank <400)');
   break;
  case "4":
   array_push($aORs,'(rank >=0 AND rank <300)');
   break;   
 }
}

$Query .= implode(" OR ",$aORs); //transform the array of criteria into a properly delimited WHERE clause...

$Query .= ") ORDER BY lastname, firstname";

$Result=mysql_db_query($DBName,$Query,$Link);//execute the query

Don't focus so much on the switch/case statement as you do on the fact that every time I create a new OR statement, I'm pushing it onto my $aORs array. After I've created all of the needed ORs, I invoke the 'implode' function and spit out a nice WHERE clause where each statement is separated by " OR ".

Resulting SQL:

SELECT userid,firstname,lastname,username,password
FROM UserTable
WHERE ((rank >=700 AND rank <100000) OR (rank >=500 AND rank <700) OR (rank >=300 AND rank <400))
ORDER BY lastname, firstname


You can use this same approach any time you need to create some kind of delimited list of values. All you have to do is replace the first parameter in the 'implode' function with whatever you need the delimiter to be.

Hope this helps.

Posted by dougboude at 11:40 AM | PRINT THIS POST! | Link | 3 comments
20 May 2009
Basic Ajax Select List Filter in PHP

I am a ColdFusion guy, without a doubt. At my new job, however, I have inherited the maintenance and enhancement duties of a large PHP application as well. One of the enhancements I was asked to make was to produce a select list of names that could be filtered on the fly as the user typed into a text box. Being somewhat new to PHP and having had to figure out a good approach to creating this feature, I thought I'd share it in case it helps someone else.

Picture if you will, a select list filled with names and immediately below it a text box for filtering that list. Better yet, here's what mine looks like:

 select list with ajax name filter


As the user begins typing in the text box, the select list begins to be filtered, re-filtering as each letter is added or removed.

I'm using the Prototype javascript library to perform the ajax calls, and a PHP script I call "adminAjax.php" that listens for and responds to those ajax calls. First off then, the HTML and JS that sets up the user interface:

<div id="namelist" name="namelist" style="height:350px;width:200px;"></div>
<div>
 Last Name: <input type="text" id="fltName" name="fltName" size="25" />
</div>

<script>
 Event.observe(window, 'load', function() {
  Event.observe('fltName', 'keyup', function(e){filterByName(e);});
  filterByName('');//this initially populates the select list with ALL names...
 });
</script>

 

basically, I have one div that will hold the select list ("namelist"), and some js that, on page load, will bind the 'filterByName' function to the keyup event on the 'fltName' textbox. So, with every character entered or removed from that textbox, the current value will be passed to the filterByName function. Here's the filterByName function:

function filterByName(strname){
 var params = new Hash();
 params.set('namestring',strname);
 params.set('actionval','getSelect');
 new Ajax.Updater('namelist','adminAjax.php',{parameters:params,method:'get'});
}

 

Okay, now on to adminAjax.php.

I'm using this template exclusively for ajax responses, so what I did was to create a switch/case statement that routes to the appropriate function based on the incoming 'actionval' parameter. Important to note: in my case, I chose to create the entire select list on this end and then return the completed HTML. The Updater that made the Ajax call will then place the returned HTML into the target div for us. Here's the code:

<?
 //make sure we have a default value for the actionval parameter...
 if(!isset($_GET['actionval'])){$_GET['actionval']='none';}
 
 switch ($_GET['actionval']){
  case 'getSelect':
   $retval = getSelect();
   echo $retval;
   break;
  case 'some_other_action':
   $retval = bogusCall($_GET['someParam']);
   echo $retval;
   break;
 }

 //end of our switch router! Now for the functions that feed it...

 function getSelect(){
  include("settings.php");
  $Query = "SELECT userid,firstname,lastname from myTable ";
  $Query .= " where firstname <> '' and lastname <> '' ";
  
  //filtering on lastname/firstname...?
  if(isset($_GET['namestring']) && strlen($_GET['namestring'])>0){
   $aStr = split(",",$_GET['namestring']);
   $len = strlen(trim($aStr[0]));
   $flen = (count($aStr) > 1)?strlen(trim($aStr[1])):0;
   $Query .= "AND SUBSTR(lastname,1,".$len.") = '".trim($aStr[0])."' ";
   if($flen > 0){
    $Query .= "AND SUBSTR(firstname,1,".$flen.") = '".trim($aStr[1])."' ";
   }
  }
  $Query .= "order by lastname,firstname";

         $Result=mysql_db_query($DBName,$Query,$Link);

         if(mysql_numrows($Result) == 0){
          $strField = "<br><br>No Records Found. Please Change Filter Values and Try Again.";
         } else {//we have some records...let's build the select list HTML.
   $strField ='<select name="selUsers" id="selUsers" size="20" style="width:200px;" >';
   while($row = mysql_fetch_assoc($Result)){
    $strField .= '<option value=\''.$row['userid'].'\'>'.$row['lastname'].', '.$row['firstname'].'</option>';
   }
   $strField .='</select>';
         }
         mysql_close();
  return $strField;  
 }

That's it!

You may be thinking what I was originally thinking, something along the lines of "wouldn't it just be faster to have given the page a json representation of all the names, then used JS to filter it on the client side?" Well, the answer (at least in my case) is NOPE. I am working with about 3,000 names, and my first approach was to do it using the JSON data. This worked fine in Firefox, but IE...of course it ran painfully slow. Using the Ajax approach and just creating a new select list as the filter value changes works surprisingly fast in all browsers!

Hope this helps.

If you would like a good set of starter snippets, you can grab the zip file here.

 

 

Posted by dougboude at 2:02 PM | PRINT THIS POST! | Link | 1 comment