Tuesday, December 2, 2014

Alternating Background Images

Today I want to show you how in just a few lines of jQuery code we can alternate or swap out the background image for any ID or CLASS.

The task of changing the CSS properties and setting a new background image is much simpler than you might expect and you may even find my method is quite a bit easier than other examples you've found. So, let's get into it shall we?

In the HEAD portion of your HTML document you'll need to include a link to the latest jQuery file. As you'll see from my example below, I'm linking to the jQuery site itself, but you could of course use Google's hosted jQuery library or even download a copy to your system and place it in a sub-folder to the site.

<script type="text/javascript" src=""></script>

The upside to linking to a hosted library is speed and accessibility. While you may think that having a copy of the jQuery library  on the website itself would be faster to load, you would be wrong. Linking to a hosted library, and specifically to the minified version of jQuery, will almost always be a faster download for the client because the chances of having that hosted server in closer proximity to the client are pretty good.

But I digress... once you've got your minified jQuery link set we're ready to add in our code to change the CSS properties and swap out the background image for any given ID or CLASS.

The jQuery code itself is extremely simple and looks like this:

    var $img = 2;
    function cycleImages(){   
        if($img >6) {
            $img =1;
         setInterval('cycleImages()', 3000);


We start off with declaring our variable, in this case $img, which as you can see I've set to 2, to which you'll find why in a moment. You should also note that the variable is declared above the function. This is especially important because if we were to declare it inside the function then the same image would get set as the background image which defeats our purpose here.

We then setup our function which I'm calling cycleImages, though you can name it anything you want.

Inside the function we first modify the CSS for ID header, which is the ID I want the background image transition to happen in, and set it to none in case there was a previous setting for the background-image for this particular ID.

Next we check to see is our variable is over a predefined limit. Why you might ask? Well, in this scenario I only have 6 banners I want to display, appropriately named: banner1.jpg - banner6.jpg, so it only makes sense to limit the background image swap out to those same 6 images.

 If we discover $img is over the count of 6 during our limit check, then we simply set it back to 1 to start the whole sequence over.

 Next we modify the CSS property again for our ID header, but this time we set the background image to our banner + our image count, which is our variable $img. The plus signs in that line of code simply ties the string together.

After we display the new background image we increase the count for our variable $img by 1 so when the function gets called again, we're all set to display the next banner image.

The window load function simply says wait until the window (read page) is loaded, then do this. Within that function we've set a delay (setInterval) to run our other function (cycleImages) every 3000 milliseconds, or about every 3 seconds.

Now, getting back to why I set the $img variable to 2 originally. It's because I previously defined the background-image for #header to background-image: url(../images/backgrounds/banner1.jpg); in my CSS file. And there's no sense in repeating that same image twice.

 And that's all there is to do. Pretty simple huh?

Tom M. Wiseman
Digital Dreams

Tuesday, September 2, 2014

HTML Form Preparation

Today I want to discuss preparing the data a user would enter into one or more HTML forms you might have on your website prior to sending it off to a script for processing.

While many of these tasks could be performed on the server side within the processing script, I think it's important to get into the habit of sending the data in it's proper form & format that the script will expecting it in, especially if that data will be saved to a database.

To begin, let's take a look at a very common HTML Sign Up form...

<form action="./scripts/register.php" method="post" enctype="multipart/form-data" id="registeruser" name="registeruser">
            <fieldset class="fifty">
                <input name="First" type="text" size="10" maxlength="25" autofocus id="First" placeholder="First Name" />
            <fieldset class="fifty">
                <input name="Last" type="text" size="15" maxlength="25" placeholder="Last Name" />
            <fieldset class="fifty">
                <input name="Middle" type="text" size="1"  maxlength="1" placeholder="Middle Initial" />
            <fieldset class="fifty">
                <input name="Username" type="text" size="25" maxlength="25" id="Username" placeholder="Enter A Unique Username" onBlur='lowerCase(this)'><br /><br />
            </fieldset><br /><br />
            <label>Avatar Image: </label><input type="file" size="32" name="myavatar"  /><br /><br />
            <label for="pass"></label>
            <input id="pass" name="pass" type="password" value="" placeholder="Password" />
            <label for="pass2"></label>
            <input id="pass2" name="pass2" type="password" value="" placeholder="Password Validation" /><br /><br />
            <fieldset class="fifty">
                <label>Secret Question: </label><br /><select name="SecQue">
                    <option>Mothers Maiden Name?</option>
                    <option>Year You Were Married?</option>
                    <option>Birth City?</option>
                    <option>Best Friends Name?</option>
                    <option>First Pets Name?</option>
                    <option>Favorite Childhood Toy?</option>
                    <option>Year Graduated High School?</option>
                    <option>Make of First Car?</option>
                    <option>First Company You Worked For?</option>
                    <option>Oldest Childs Middle Name?</option></select>
            <fieldset class="fifty">
                <label>Secret Answer: </label><br /><input name="SecAns" type="text" size="40" maxlength="80" id="SecAns" placeholder="Secret Answer - Keep in safe place"><br /><br />
            <fieldset class="fifty">
                <input name="Phone" type="tel" size="12" maxlength="18" id="Phone" placeholder="Phone Number Including Area Code" onBlur='addDashes(this)'>
            <fieldset class="fifty">
                <input name="Email" type="email" size="15" maxlength="40" id="Email" placeholder="Email Address"><br /><br />
            <fieldset class="fifty">
                <input name="Address" type="text" size="20" maxlength="35" id="Address" placeholder="Street Address">
            <fieldset class="fifty">
                <input name="City" type="text" size="10" maxlength="25" id="City" placeholder="City"><br /><br />
                <h5>*If INTL please use OTHER for State and INTL for Country.</h5>
                <label>State: </label><select name="State" size="1">
                <label for="Zip"></label><input name="Zip" type="text" size="5" maxlength="15" id="Zip" placeholder="Zip Code">
                <label>Country: </label><select name="Country" size="1"><option>USA</option><option>CAN</option><option>INTL</option></select>
            </fieldset><br /><br />
                $time = date("\a\\t g:ia", time());
                $month = sprintf("%02s", $my_t[mon]);
                $ErrorDate =("$my_t[year]-$month-$my_t[mday]");
                echo '<input name="LastLogin" type="hidden" id="LastLogin" value="'.$ErrorDate.'">';
            <input name="submit" type="submit" value="Submit" id="submit" />
            <input name="reset" type="reset" value="Reset" id="reset" />           

As you can see, while there are only a handful of fields that a user must fill out, the form itself is slightly complex. Why? Well, that's what we're going to discuss here.

As you can see we're using our fieldset tags to identify specific sections of the form, which help the browser identify those sections and neatly display them as such. Furthermore, I am styling the form in part by using the class of "fifty" which is .fifty{width:50%;float:left;clear:none;} in my CSS file.

Additionally I like to make use of the size and maxlength where ever it makes sense to do so, so the data is formatted correctly per the database's table I'll be storing to. Using these two attributes not only make for a cleaner looking form, but it will prevent strings from being too long when I go to process them.

For the State field, instead of having a simple text area or text input here, I choose to use a drop-down with all of the states already listed within individual options. That way a user can't possibly misspell it and I won't have any issues later when it gets saved to the database.

For the Username & Phone Number fields, you might have noticed the "onBlur" attribute. This attribute when defined will send the information to a jQuery script for further pre-formatting. In this case I have 2 scripts. For the Username I am converting all of the characters to lowercase before sending it off to my script, and for the phone number, I'm adding dashes between the area code & prefix. (i.e. TWiseman become twiseman, and 5105551211 becomes 510-555-1211).

And as you might have guessed, the jQuery script gets ran as soon as the user shifts focus to any other field, hence "onBlur".

There are a few different ways to make it easy for your users to understand what data they need to enter into any given field. One of the simplest and most common ways is to include a label, which as you can see we're using quite a bit here.

Another way is to use the attribute placeholder="some text"which if included within a standard text input field will display whatever you place in the quotes inside the field itself. And what's neat about this attribute, is it disappears when a user starts to type something into that field and will reappear if they click the Reset button or if they remove whatever they had typed there.

Of course a third way would be to set the value attribute. Personally I don't like to do this though unless I'm pulling information from the database and need to show the user what's already been saved there (i.e. for a Profile page or something). The reason is because a user would need to completely remove the data within that field before being able to type something new, which complicates the process unnecessarily.

When dealing with passwords it's important to verify what the user typed in. We could send the data from both of those fields to a jQuery script (which would definitely be my recommendation) to see if they both match before allowing the user to click Submit, or, you can simply compare them both on the back-end within the processing script like I'm doing here.

Either way, make sure you verify those passwords. It will of course be the key to allowing a user entry into your site or a specific area of the site later on.

Both of the Password fields are set with the attribute type="password" to force the browser to display each character as an asterisk instead of showing them in plain text. For security reasons, you do not want to display a password on screen in plain text, though it should be noted that the information sent to the processing script will be in plain text unless you encrypt it on the front-end somehow.

I'm also making use of a hidden field. Why? Because I want to store the user's last login date so we have a record of when they logged in, and frankly there's no reason I need to show the user that field. So, by simply using the type="hidden" attribute, I can send over the current date (obtained by using a little PHP script embedded into the form) and dropping the data into that field.

Tom M. Wiseman
Digital Dreams

Wednesday, March 19, 2014

HTML/PHP Advanced Guestbook

The single most popular post from my blog is by far the Guestbook using HTML/PHP, which for me personally seems a little odd, but apparently it's what you wanted to know about. And far be it for me to argue with what you want to learn about.

 So, with that in mind, I thought I'd revisit that topic and lend a hand at creating a much more advanced Guestbook or Online Chatting System.

 If you read the previous post, then you already know that the basic setup is to create an HTML form to allow your users to enter in their name and some comment, then we store that information into a text file called GuestBook.dat, and finally, read in that file and display it to the users.

 The original post and information there gave an example of a very basic guestbook, and was to be honest, a bit clunky.

 To get started, first create a PHP document, and then at the very top of that document add the following code:

    if (!isset($_SESSION)) { session_start(); }
    // Advanced Guestbook | NAME | COMMENT | DATE/TIME
    // Written by Tom M. Wiseman
    // Digital Dreams - web design studio
      $today = "";
      $month = "";
      $day = "";
      $year = "";
      $person = "" ;
      $comment = "" ;
    print '<table width="700" border="1">
              <th scope="col">NAME</th>
              <th scope="col">COMMENT</th>
              <th scope="col">DATE/TIME</th>
    // Read from ("guestbook.dat");
    if (file_exists("guestbook.dat"))
      print '<tr>';
      $file = fopen("guestbook.dat", "r", 81);
      while (!feof($file)) {
          $line1 = fgets($file);
          $line2 = fgets($file);
          $line3 = fgets($file);
          print '<td>' . $line2.'</td>';
          print '<td>' . $line3.'</td>';
          print '<td>' . $line1.'</td>';
          print '</tr>';
      print "No Comments in Guestbook";
    print '</table>';

The first line simply starts up our PHP session if it's not already started so we can store variables to the session.

 After that we declare but NULL out our date, person & comment variables, to include unsetting any posted name or comment that might still be hanging around (we'll go over why we do this in a moment).

 From there, we create our basic table structure to house the information from the guestbook text file. You don't need to create a table if you would rather display the information using some other method. This is simply a demonstration and my preferred method.
 Once we have the table structure in place, we can then read in the file (guestbook.dat), line by line if it exists and display that information to the user. If it doesn't exist, then we display some sort of error or notification. In this case we're displaying "No Comments in Guestbook".

 Next comes our HTML and JQuery code:

<!DOCTYPE html>
<script src=""></script>
<script src=""></script>
    $('#input2').keypress(function() {
        var name=$('#input1').val();
        var comment=$('#input2').val();       
        $('#test').html("<b>"+name+"... is typing</b>");

The keypress function will become self-evident later in this post, and is actually not required for a guestbook. However, if you are going to use the same principles here to design an online chatting system, you will probably want to include that section.

 So the markup above simply tells the browser we're using HTML5, initializes the page with our html and head tags, links to 2 different jQuery scripts, and then defines our keypress function so we know when someone is typing something into the comment field.

 Next up we have our body tag and the form itself. Again this is a very basic form, as it should be for our purposes here.

          <form action="my_ajax.php" method="post" enctype="multipart/form-data" name="guestbook" class="contactform" id="my_form" title="Guest Book Form">            
            <label id="label">Name: </label>
            <input name="name" type="text" size="40" maxlength="80" id="input1" value="" />  
            <label id="label">Comment: </label>
            <input name="comment" type="text" size="40" maxlength="80" id="input2" value="" />
            <input name="submit" type="submit" value="Submit" id="button1" hidden/>
            Chat Session:
            <div id="test"></div>

 You may notice the lack of a RESET button. This is intentional to help keep the form looking clean, though you could certainly add one if you desired. When this form is submitted, we'll be sending the POSTed data to another PHP script called "my_ajax.php". Feel free to rename that script to anything you want, just remember to change the name in the form above.

 As you can also see, we have an ID associated with both input fields. This goes back to our jQuery function where we check to see if someone is typing within the comment field. If they are, then we display their username and the text "... is typing" within the div with the ID of test.

 To help prevent the same information from getting stored in our text file multiple times accidentally (i.e. the user refreshes the browser), we wipe out the variables at the top of this page/document. That way if any data is floating around in memory, as it often is, we he'll have a clean slate to work with each time this page is loaded up.

 And that's all that is required within the main page or document, so go ahead and save it now.

 Next we need to create our "my_ajax.php" document, so once again, create a new PHP doc., and within that document, place the following code:

    if (!isset($_SESSION)) { session_start(); }    $today = getdate();
    $month = $today[mon];
    $day = $today[mday];
    $year = $today[year];
    $person = $_POST['name'];
    $comment = $_POST['comment'];
    if ($person !="")
        $time = date("\t g:ia", time());
        file_put_contents("guestbook.dat", $date." @ ".$time."\r\n", FILE_APPEND);
        file_put_contents("guestbook.dat", $person."\r\n", FILE_APPEND);
        file_put_contents("guestbook.dat", $comment."\r\n", FILE_APPEND);
    echo '<meta http-equiv="refresh" content="0; URL=index.php">';

 At the top of this script, we have initialized some date variables as well as defined our posted data for the name and comment.
 We then check to see if the name field was filled out, and if it was, we continue. if not, we send the user back to the original page, which I named index.php.

 Within the script we define the date by gathering the Month, Day & Year, plus the time in order to store that to our text file (guestbook.dat).
 We've already grabbed the POSTed data from our HTML form, so all we need to do now is write out the data to our text file, line by line.

 The neat thing about the script above is it will automatically create the guestbook.dat file if it doesn't already exist. So there's no need to add additional scripting to check for it, or create a blank one.

 Once the data has been saved, we send the user back to the main page, where the file is re-opened and instantly displayed to the user.

 And that's it! You now have a very clean and functional advanced guestbook or online chatting system

Tom M. Wiseman
Digital Dreams

Wednesday, February 12, 2014

Project Planning & Web Design

 Proper project planning is a must-do for any project, while failure to consider all aspects of a given project before implementation can mean certain doom.

 As an Implementation Engineer, I am very much a part of the planning phase for every project I am involved with. And as such am accustomed to planning every step as well as establishing success & failure factors. In my Website Designing business, I carry over those same principles with me because they are no less important there.


 Proper planning means to consider every aspect of a given project, including the client's needs, workflow, and customer base. In general you'll need to consider what the end result should look like, feel like, and what the success factors will be. Another words, what are you trying to accomplish and how do you calculate success or failure.

 When it comes to designing websites you may be inclined to just jump right in and start designing something based on your first client meeting or call, or worse, on your intuition. But I can tell you from experience that that's the worse way to approach a project.
 Consider this... you go out on a limb and spend days or even weeks designing something that you think is appropriate and then show it to the client. The client ends up hating most or all of it, forcing you to go back to the drawing board and start fresh, or worse, they decide to go elsewhere.

 Not only have you lost a bunch of time, but you might have lost a customer as well, and if the latter, that probably also means the beginnings of a bad reputation which can absolutely kill your business.

Ask and You Shall Receive

 During your first meeting or call with your client you should be asking things like: Who is your competition, what message do you want to relay to your online visitors, what do you expect from your website in terms of Search Engine ranking, number of hits per day, and effect on the bottom line.

 Don't be afraid to explain these terms to your clients. They're likely unfamiliar with them and would appreciate an explanation so they can understand what it is you're asking as well as what their website can do for their business. Just be careful not to talk down to them. You don't want to come off sounding like a egotistical know-it-all, but merely an experienced professional.

 Most of my customers have no idea what they want out of a website other than to generate more income. And we know that's pretty much a given for any website, right? However, there's nothing wrong with asking how much of an increase they might expect, keeping in mind that typically, websites alone don't generate income. Primarily they provide an online experience which will drive a visitor into the brick and mortar store front, or possibly to making an online purchase if available.

The Experience is Everything

 As the saying goes, first impressions are everything, which simply means you need to design the site so-as to engage the visitor, prompting them to stay and dig deeper. A site's bounce-rate will ultimately be your primary measuring tool for this. If the bounce-rate is high, visitors are not staying long. Additionally you'll want to keep an eye on the Avg. Visit Duration. Obviously higher numbers here mean a higher success rate in terms of keeping visitors on the site.

Another analytic metric tool is the Pages/Visit, which shows how many different pages visitors are going to on average. However, this number can be skewed and not very helpful if you have a single page website which scrolls to each section. If you have a site with multiple pages though, then it's certainly something to look at, but don't get overly concerned if the numbers stay relatively low for this metric. Ultimately you'll need to make your impression on the first page users hit, which is not to say the rest of the pages should be thrown together with no regard for lasting impressions, SEO, or anything else, but simply that the first page should be your primary focus when first designing the site.

SEO & Search Engine Placement

 Everyone wants to be listed at the top of a search engine, and while there are many things we as designers can do to help make that happen, the bottom line is that a site's placement is left to the algorithm for any given search engine (i.e. Google, Yahoo, MSN).

 Personally I do not promise my clients that I can get them to top. Why? because I know that whatever I do SEO-wise may not be enough. There are tons of factors when considering where a site will be placed in a search engine's list, including Site Description, Keywords, Img Alt tags, use and placement of H1, H2, H3, H4, H5, strong, em, and even p tags, word combinations among paragraphs, and a little lesser known factor, how often people search for that site or words that the site uses.

 So what I'm saying is that while you definitely want to consider all of the details surrounding SEO; planning appropriately, designing correctly, modifying if necessary, the end result may not be what you or your client desired. To that end, don't promise the world when it comes to search engine placement. Be honest and inform your clients that you'll take all of the necessary steps to get them ranked as high as possible, but that you don't control the algorithm behind creating the list.

Colors / Themes

 I know that I have talked about this basic principal time and time again in other posts, but I would be remiss if I didn't mention it again here. Using the right color palette, layout & theme for your client's site will go a long way in making that first impression I spoke about earlier.

 If you think that colors or themes don't matter or that anything will do, you would be vastly wrong. When considering what color shades to use (dark or light, flat or brilliant) you have to consider the audience. If we're creating a site for a Tattoo shop or an industrial business of some sort, then using  darker shades for the theme would be okay, but you wouldn't want to use those same colors for say a beauty salon or photography shop.

 If you're completely at a loss as to which colors to go with for any particular project, start with the client's logo. Use colors and shades that compliment the logo.

Picture is Worth a Thousand Words

We've all heard this before, but it is no less relevant to website designing. The right picture placed in the right location will speak to the visitor in ways words may not be able to. But like everything else, moderation should always be applied, as well as good sense. If the image doesn't help to relay the message, don't use it.

Plan It All Out

 So to put all of this together, here's the basic steps/notes to take when planning your website design project:

 1) Ask your client questions, even if takes several meetings or calls to accomplish. Find out everything you can about their business so you can get a feel for who their clientele will be.

 2) Think about what message the site needs to relay, which will help you to use the correct keywords and tags as well as word-combinations when dealing with the content and SEO.

 3) Plan out the layout, possibly even wire-framing it before beginning to code the site. Draw it out on paper if you must, but somehow or another you need to get a mental picture as to where content will be placed, making sure to consider the overall message.

 4) Carefully choose your color palette, ensuring the colors and theme blend well with the client's logo and/or business type.

 5) Decide how you can make the site interactive without overdoing it. What features can you implement that will help keep a visitor on the site and going from page to page to learn more.

 6) Code it and test it. Make sure you test from multiple devices as well as browsers. All browsers don't behave the same, so just because it works in one doesn't mean it will work in all.

 7) Keep an eye on the site's statistics at least for the first 30 days after implementation and tweak anything that needs to be tweaked such as keywords and what not.

Tom M. Wiseman
Digital Dreams

Sunday, December 8, 2013

Form Validation Using jQuery

 How many times have you sat down and designed a login form of some sort for a client only to get frustrated with it because you couldn't figure out a way to validate the information the user entered before sending it off to your script for processing?

 Well, that's about to change, because what we're going to cover today is exactly that. An easy way to validate any form input using some simple markup and jQuery.

 But before we get into the solution, let's take a look at a standard form and the typical flow of processing that data. First we have the HTML form itself:

 <form action="register.php" method="post" enctype="multipart/form-data" name="register" id="register" >
      <input name="First" type="text" size="10" maxlength="25" autofocus id="First" placeholder="First Name" /><br /><br />
      <input name="Last" type="text" size="15" maxlength="25" placeholder="Last Name" /><br /><br />
      <input name="Middle" type="text" size="1"  maxlength="1" placeholder="Middle Initial" /><br /><br />
      <label for="Username"></label><input name="Username" type="text" size="25" maxlength="25" id="Username" placeholder="Enter A Unique Username"><br /><br />

      <input id="pass" name="pass" type="password" value="" placeholder="Password" />
      <input id="pass2" name="pass2" type="password" value="" placeholder="Password Validation" /><br /><br />

      <input name="submit" type="submit" value="Submit" id="submit" />
      <input name="reset" type="reset" value="Reset" id="reset" />


 Naturally after a user enters the data and clicks the submit button, the data is sent over to a script, usually a PHP script, for processing where we pull in the POSTed data and do whatever it is we're going to do with it.

  As you can see I'm not a fan of using labels. I prefer a more clean look to my forms and use the placeholder tag instead. However, in order to accomplish the validation we'll need to drop in labels for each field we want to validate. The good news though is we don't actually have to have any text inside the label, so essentially it's hidden to the user.

<form action="register.php" method="post" enctype="multipart/form-data" name="register" id="register" >
      <label for="First"></label><input name="First" type="text" size="10" maxlength="25" autofocus id="First" placeholder="First Name" /><br /><br />
      <input name="Last" type="text" size="15" maxlength="25" placeholder="Last Name" /><br /><br />
      <input name="Middle" type="text" size="1"  maxlength="1" placeholder="Middle Initial" /><br /><br />
      <label for="Username"></label><input name="Username" type="text" size="25" maxlength="25" id="Username" placeholder="Enter A Unique Username"><br /><br />

      <label for="pass"></label>
      <input id="pass" name="pass" type="password" value="" placeholder="Password" />
      <label for="pass2"></label>
      <input id="pass2" name="pass2" type="password" value="" placeholder="Password Validation" /><br /><br />
      <input name="submit" type="submit" value="Submit" id="submit" />
      <input name="reset" type="reset" value="Reset" id="reset" />


 So the new form has 2 labels, one for each of the password fields, which happen to be the same fields we're going to validate with our jQuery script. Again, there's no need to have any text within that label tab, and in fact I would recommend against it to help keep your forms looking clean.

 With the form in place we now need a link to a jQuery validation and general use script. Here's the two that I tend to use most often which also allow you some flexibility when it comes to tweaking your internal calling script. Both scripts below are minified to save load time.

     <script src=""></script>
     <script src=""></script>

 The validate.js script I use comes from Rick Harrison, which is completely free to download from his site if you wish to use a local copy.
 You should also check out his site for all of the nitty gritty details plus some examples of use.

 And finally all we need is the calling script, which again can be tweaked in a variety of ways.

    // validate signup form on keyup and submit
         rules: {
              pass: {
                    required: true,
                    minlength: 5,
                    maxlength: 15
              pass2: {
                    required: true,
                    minlength: 5,
                    maxlength: 15,
                    equalTo: "#pass"
         messages: {
              pass: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long",
                    maxlength: "Your password cannot be more than 15 characters long"
              pass2: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long",
                    maxlength: "Your password cannot be more than 15 characters long",
                    equalTo: "Please enter the same password as above"

 As you can see, we call validate.js using the ID of the form, which in this case is register. Below that we have 2 sections, 1 for the rules and another for any message we plan on showing to the user.

 In the rules shown we're not only telling validate.js that the field can't be blank (required: true) but we're also setting the minimum and maximum lengths or number of characters. We have this set so that the password the user selects will comply with the maxlength value we have set in the database for the password.You'll also notice that pass2 has an additional rule, equalTo:"#pass", which simply tells validate.js that the 2nd password entered must match the first one exactly.

 The messages section is exactly that. What if anything will we display to the user if one or more input fields don't comply with the rules. Here we've added some very simple messages, but naturally these can be edited to suit your needs. However, don't get too wordy, otherwise your form could get completed distorted (input fields could move out of place) due to the length of your message.

 A great thing about Rick's validation script is the ease of which you can tweak the calling script to suit whatever needs you may have. If you want to validate the username, you can do that. If you need to validate a number or email, you can do that too.
 Another awesome feature to the validate.js script is the fact that all of the styling comes built in, so there's absolutely no need to add anything extra to your CSS dealing with the message output.

 A word of caution though... your form MUST contain a few specific items in order for validate.js to do it's job. One, each input must have a label as shown above. Two, each input must have an ID with the exact same name as the label, and three, the form itself must have a unique ID.

 And there we have it... a brand new HTML form complete with self-validation.

Tom M. Wiseman
Digital Dreams

Tuesday, September 24, 2013

Flat Design - Passing Fad or New Staple

 As you no doubt have heard, many designers have or are turning to flat design. And there appear to be several reasons for this many of which reflect solely on that designer's personal preference, but if you think the reasons stop there, read on.

 Flat design is a style that lacks the “tricks” designers often use in order to create a realistic or three-dimensional effect. The style is characterized by an overall minimalistic look, bright but muted colors, bold - often retro typography and simple user interface elements such as buttons or icons.
Flat design techniques avoid embellishments such as bevels, embossing, drop shadows, gradients or artificial textures. Typically you will see flat designs used in mobile applications or in web sites with only a few pages, and rarely if ever will you find any sort of animation in a flat design.

 So this begs the questions: Why would you use it or when should you use it? Unfortunately there's no short answer to either of those questions, but we can at least outline a few possibilities.

 One of the biggest benefits to flat design is the simplistic and/or minimalistic approach. This technique lends itself well to scalable websites, which is to say sites that make use of media queries that will render the content based on the user's screen resolution, otherwise known as responsive design.

 Another benefit is the shortened development time.  A six page site built using flat design may only take you 3-4 days to design/develop due to the simplicity of it all, while the same site using a more stylized approach will likely take twice that long.

 While still another benefit is to allow the content to speak for itself, rather than tossing a bunch of unnecessary graphics and animation at a user, which frankly they probably don't care about anyway, flat design allows the user to immerse themselves into the unfolding story, focusing more on the content.

So you might be saying right about now, great, let me get started... but wait. There are some down-sides to this style, and I would be remiss if I did not point them out.

 One obvious downside would be the use of "cartoonish" style graphics. And while this may go hand-in-hand with the overall concept, I find those sort of graphics a bit underwhelming and not so appealing. Though that being said, the use of cartoon looking graphics is not a prerequisite.

 And while this style initially appears to be very easy to tackle, once you launch down that path you'll quickly realize that the lack of bevels, drop shadows, gradients and other elements often included in other styles make the remaining elements much more relevant. If the colors don't blend well or you use the wrong style icons, your website will end up looking very amateurish and will not gain the popularity and respect you'll desire. In short, it'll be deemed a flop.

 The structure or layout of the site should also take precedence when using flat design. This is not to say that the structure for any other style should be deemed as less important, but when you're talking flat design, the order of content becomes especially important to the user's overall experience.

 Take aways... before venturing off and designing a flat design website just because it's the latest trend, make sure you do your homework and take into consideration if a flat design will ultimately be the best style to reflect the business you are designing for. Additionally you'll want to consider the demographics of the clientele the business expects to see or is targeting, plus keep in mind the various interfaces through which a user will be accessing the site.

 I think when done right a flat design can go a long way to help with marketing and branding, and specifically the targeting of content, but I'm not so sure many designers have the know-how or patience to get all of the pieces together in the correct order.

Tom M. Wiseman
Digital Dreams

Thursday, September 12, 2013

MySQL Databases & PHP Scripting- Part V

 I know it's been a couple of months since the last post, but it's time to round out this 5-part series with information on how to create and check browser-side cookies plus generating HTML encoded e-mails.

 To get us rolling let's do a quick review about the previously discussed method for tracking a user's session. In Part II of this series:, I outlined how to create a session variable when a user logs in, and then how to check to see if a user is already logged in by checking if our session variable is set (as shown below).

   if isset($_SESSION['USER'])
      // User is logged in. Show the rest of the page or information as applicable
        // User is not logged in. Take them back to the homepage.
        header("Location: ../index.php?action=no");

 What we'll focus on today is a slightly different approach and a bit more comprehensive than just having a server-side session variable.

 Creating a browser-based cookie is a fairly simple process but you'll need to keep some things in mind before delving into it. First and foremost is you cannot create a cookie, which is to say store a cookie on a users system, after any HTML header is applied (i.e. <!DOCTYPE html>). What this means is that you'll need to generate the cookie BEFORE the header.

 Second, you'll need to think deeply about the needs and requirements of the site you are developing for to correctly decide how long the cookie will be valid for. More times than not you'll see sites who expire a cookie after only an hour or two, but there are times that you'll want/need to increase this to say 24 hours. Use caution though. The longer the cookie is valid for the weaker the security becomes and greater becomes the possibility of compromise. Since the whole purpose is to validate a user's session while giving them the flexibility to stay logged in for a set duration, you would not want to make the expiration much more than 24 hours, or worse, indefinitely. Doing so defeats the whole purpose.

 So, with that in mind, let's proceed. While there are certainly different methodologies to creating browser-side cookies, I find that creating two of them, one to hold a random string and one to hold the expiration works best for me. We'll get into why I use this approach shortly.

 Like I mentioned before, creating a cookie is fairly simple. All you need to do is create an expiration variable based on the current time, and a random set of characters that will get stored as a single string.

   $expire=time()+(60*60); // 60 minutes
   $RandString = substr(md5(rand()), 0, 25);
   setcookie("CookieExpire", $expire, $expire);
   setcookie("CookieLogin", $RandString, $expire);

 Time in PHP can be a little confusing, but what is returned if you were to write something like "echo 'Time: '. time();" is the time in seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
 And as you can hopefully see what I've done in the example above is created an expiration variable based on the current time, and added (60 seconds times 60 minutes). So I'm setting the expiration to one hour ahead of the current time.

 Then in the next line I'm merely generating a 25 character string based on md5, which simply calculates the MD5 hash of a string, or in layman's terms, encrypts a string based on the widely accepted Message Digest Algorithm.

 The next two lines create two cookies using the variables previously assigned. The first cookie stores the expiration time while the second stores the encrypted 25 character string.

 As I mentioned 5 paragraphs ago, there is a legitimate reason why I use 2 cookies and not just 1.

When we go back to check the cookie, which is to say look at the contents to discern whether a user is still logged in or not, we could theoretically check the contents of CookieExpire and compare it against the current time to see how long is left. However, if in our code we have already set a header, we won't be able to grab the contents. This becomes critical when considering you are likely to have multiple pages within a given website and you'll need to check this same cookie throughout each page.
 The second reason is for additional security. With a simple time stamp applied to the cookie, it would be relatively easy for someone to change the cookie contents and gain entry to our system if that was the only cookie we had set. If we set two cookies, with one containing a random encrypted string, then we have increased security to our system by at least 3 fold, plus it gives more flexibility to add other validating functions such as storing the cookie to a database and checking against that as well.

 After our cookies are set, we can check them to validate if a user is still logged in or not. And we do that by first checking the expiration cookie. Again, you could simply check the cookie itself, but I find that a more reliable method is to store the cookie contents in a separate session variable like so:

 $_SESSION['EXPIRE'] = $_COOKIE['CookieExpire'];
 $expires = round((($_SESSION['EXPIRE']-time())/60),0);
 $_SESSION['LOGIN'] = $_COOKIE["CookieLogin'];

 This allows me to move from page to page and still have the ability to check that expiration if I want or need to since the expiration is now stored in a session variable, and as long as I begin each page with a session_start(); I can check or change any session variable I want.

 So my code to actually check the expiration would be:
 if (isset($_SESSION['LOGIN']))

    if ($expires <=0)
        // User's cookie has expired and needs to login again
       // User is still logged in.
   // User does not have a cookie and needs to login

 Once you know whether or not they are still logged in or if they even have a cookie stored, where you go from here is completely up to you. Personally I unset the session variables pertaining to the login and set the cookies to the past if the expiration has timed out, which acts as an additional security function.

       setcookie("CookieExpire", "", time()-3600);
       setcookie("CookieLogin", "", time()-3600);

 However, you could elect to just send them to the registration or login process depending on if they simply expired or if they don't have a cookie stored.

 And that pretty much covers storing and retrieving browser-side cookies. Again, there's different approaches to every problem. Your challenge as a developer is to code the most applicable solution for your given project/client.

 Let's move ahead to sending an HTML encoded e-mail, which is very similar to the standard way of sending an e-mail with a few minor exceptions.

 Typically you would have a user enter some basic information into an HTML form and then after pressing submit they're re-directed to a PHP script which pulls the POSTed variables at which time you can use something like this:

$to = "";
$subject = "Contact Form";
$message = $_POST['Message'];
$sent = mail($to, $subject, $message, $headers ) ;
if ($sent)

   // Inform user the e-mail has been sent
   // Inform user e-mail was not sent.

 The above method works great if all you need to send is a plain text e-mail. But if you want to spruce it up, need to e-mail information in a specific format like a table, or want to be able to attach anything, then you'll need to send it with HTML encoding.

 And what's great is it really only take 2 additional lines.

    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

 Simply add these two lines above the if($sent) line in your script and you're all set. Additionally you can add other items to the header like what is shown below.

    $headers = "From: " . strip_tags("") . "\r\n";
    $headers .= "Reply-To: ". strip_tags("") . "\r\n";

    $headers .= "CC: "strip_tags("") . "\r\n";

 As you can see, creating an HTML formatted message is simpler than you might have thought.

 I hope everyone enjoyed this 5 part series and actually learned a few new things along the way.

Tom M. Wiseman
Digital Dreams