Design Blog Finalist Badge

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 the users wanted to know about. And far be it for me to argue with you want to learn or know 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:

<?php
    if (!isset($_SESSION)) { session_start(); }
    // Advanced Guestbook | NAME | COMMENT | DATE/TIME
    // Written by Tom M. Wiseman
    // Digital Dreams - web design studio
    // www.digitaldrms.com
      $today = "";
      $month = "";
      $day = "";
      $year = "";
      $person = "" ;
      $comment = "" ;
      unset($_POST["comment"]);
      unset($_POST["name"]);
 
    print '<table width="700" border="1">
                 <tr>
              <th scope="col">NAME</th>
              <th scope="col">COMMENT</th>
              <th scope="col">DATE/TIME</th>
              </tr>';
 
    // 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>';
      }
      fclose($file);
    }
    else
    {
      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>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#input2').keypress(function() {
        var name=$('#input1').val();
        var comment=$('#input2').val();       
        $('#test').html("<b>"+name+"... is typing</b>");
      });
});
</script>
</head>

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.

<body>   
        <div>
          <p>&nbsp;</p>           
          <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/>
            </form>
            Chat Session:
            <div id="test"></div>
     </div>
</body>
</html>

 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:

<?php
    if (!isset($_SESSION)) { session_start(); }    $today = getdate();
    $month = $today[mon];
    $day = $today[mday];
    $year = $today[year];
    $person = $_POST['name'];
    $comment = $_POST['comment'];
     
    if ($person !="")
    {
        $date=$month.'/'.$day.'/'.$year;
        $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.

Overview

 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" />

</form>

 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" />

</form>


 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="http://code.jquery.com/jquery-1.7.2.min.js"></script>
     <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></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. http://rickharrison.github.io/validate.js/
 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.

$(document).ready(function(){
    // validate signup form on keyup and submit
    $("#register").validate({
         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: http://digitaldreamwebdesigns.blogspot.com/2013/05/mysql-databases-php-scripting_28.html, 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).

 <?php
   session_start();
   if isset($_SESSION['USER'])
   {
      // User is logged in. Show the rest of the page or information as applicable
    }
    else
    {
        // 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
   }
   else
   {
       // User is still logged in.
   }
}
else
{
   // 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.

       unset($_SESSION['LOGIN']);
       unset($_SESSION['EXPIRE']);
       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 = "admin@yourdomain.com";
$subject = "Contact Form";
$message = $_POST['Message'];
$sent = mail($to, $subject, $message, $headers ) ;
if ($sent)
{

   // Inform user the e-mail has been sent
}
else
{
   // 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("admin@yourdomain.com") . "\r\n";
    $headers .= "Reply-To: ". strip_tags("DONOTREPLY@yourdomain.com") . "\r\n";

    $headers .= "CC: "strip_tags("admin@yourdomain.com") . "\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

Tuesday, July 23, 2013

MySQL Databases & PHP Scripting- Part IV

  Are we having fun with PHP yet? I hope the answer is yes, and it only gets better from here.
Previously we've covered quite a bit of ground going over how to create our initial database structure, complete with a few tables to get us going, plus the scripts to add to those tables as well as pull data from them.

 Today we're going to get into how to update those same tables and how to write to a log file so we can track what's going on within the web site.

 So as we've learned previously, when inserting data into a table we need to use the INSERT INTO command along with the table we want to toss the data into, plus of course the column names and the data itself.
 When we want to pull the data back out, which is to say read from a table, we use the SELECT command and choose the what columns to read plus the name of the table.

 So following this same line of thinking, when we want to update a column in a table, we can use the UPDATE command, which would look something like this: 

   $sql="UPDATE %TableName% SET %ColumnName%='$%Variable%' WHERE RecNo =1";

 You'll need to edit the above script however and change out the elements with percentage signs around them, but hopefully you get the idea.

 And don't forget to include your WHERE clause unless you really intend to update every single row within that column.

 Table updates really don't have any variations from what was just shown, so I think it's safe to move on.

 I have unfortunately found out the hard way that logs can be a very handy tool to have in your arsenal. A log file will help you track down problem areas on the site as well as help to develop the big picture on how the site is being used, which can also be handy when considering performance issues and knowing where, and possibly even how, to tweak your scripts.

 Writing to a log file is pretty easy and straight forward, but we do need some initial values in place before we can implement the script.
 We'll need a variable to grab the current date, another to store the current date in the correct format, another to store the time in the correct format, plus one more to hold our log file location and file name.

 So, we'll use $my_t to grab the current date.
          $my_t=getdate(date("U"));

 Then $time to store the date & time in a format that's easy to read.
          $time = date("\a\\t g.i a", time());

 Now we'll use $month to format the month into a 2 decimal integer.
           $month = sprintf("%02s", $my_t[mon]);

 Then to put these variable to use, we'll use $LogDate to stuff all of those variables into one.
          $LogDate =("$my_t[year]-$month-$my_t[mday]");


 Now all we need is some sort of error or log code (text) and the file location to write to.
         $LogData = "$Username logged into site.";
           $LogFile = "../logs/log.txt";

 And now we'll stuff those last two variables into one to make it easier to use.
         $Logged = $LogDate.'  '.$time .': '.$LogData."\r\n";

 And finally we can check to see if the file exists, and if so, write something to it, otherwise, create the log file on the fly.
          if (file_exists($LogFile)) {
                file_put_contents($LogFile, $Logged, FILE_APPEND | LOCK_EX);
            }
            else
            {
                file_put_contents($LogFile, $Logged);
            }

 So, to put it all into perspective, this is what the final script would look like:

            $time = date("\a\\t g.i a", time());
            $month = sprintf("%02s", $my_t[mon]);
            $ErrorDate =("$my_t[year]-$month-$my_t[mday]");
            // Write information to log file.
            $LogFile = "../logs/log.txt";
            $LogData = "$Username logged into site.";
            $Logged = $LogDate.'  '.$time .': '.$LogData."\r\n";
            if (file_exists($LogFile)) {
                file_put_contents($LogFile, $Logged, FILE_APPEND | LOCK_EX);
            }
            else
            {
                file_put_contents($LogFile, $Logged);
            }


 And there you have it... a functional logging script that you can drop into any section of your site in order to log whatever events you want to see.

Tom M. Wiseman
Digital Dreams
http://www.digitaldrms.com

Monday, July 15, 2013

Is Your Web Design Website Up to Par?

 Unfortunately all too often I run across web designer websites that lack... well, finesse & professionalism. They are either trying to deliver too much content to the user, have words that are misspelled, use poorly designed graphics, the site doesn't render correctly for tablet or mobile phone users, makes use of horrible color combinations, or simply has a very unstructured, hard to navigate menu system.

  And let's face it, we're supposed to be the pros. So if you're a web designer, your website better rank in the great or spectacular category. Otherwise I suspect you will have a lack of clients flowing through which means less revenue for you and your colleagues.

 There are a few simple rules to follow when designing any website, and these include but are not limited to:
  1. Scalability
  2. Search Engine Optimization
  3. Aesthetics
  4. Friendly Navigation
 Let's go over each one individually so we're all on the same page and understand the tasks at hand.
  •  Scalability is the ability of a system, network, or process to handle a growing amount of work in a capable manner or its ability to be enlarged to accommodate that growth. That means the site should be able to handle a large number of requests/hits without getting so bogged down that a user is waiting 10 or more seconds for a page to load. But it also relates to if the site was designed with different resolutions in mind, i.e. tablet and mobile phone users.
 You need to remember to create your sites in such a way that the load time is minimal. One way to accomplish this is to re-use classes and even id's in your CSS through-out several pages so as to keep the CSS as small as possible.

 Another trick is to load scripts locally and not from external sources, and only load the ones you need for that page.

 Additionally you'll want to design the site in such a way so it will be properly rendered in any environment, which means design for other resolutions other than just the monitor you use. More and more users are using the Internet from a portable device and if your site doesn't look good on those smaller devices, you could potentially be losing customers.
  •  Search Engine Optimization is the process of improving the ranking of a website on Internet search engines.
 S.E.O. should no longer be considered optional. In order for potential clients to find your website you'll need to optimize the site for search engines, and at a minimum set the Title, Description & Keywords meta tags as well as entering an ALT image tag for every image on the site.

 There is of course a ton of other ways to optimize sites for search engines, which I would highly recommend, at least for your higher end packages. Some of these would be setting the Robots meta tag, paying attention to your word structure ensuring you have good two-word & three-word combinations that directly correlate with the business, and making good use of header tags (h1, h2, h3, h4 & h5) ensuring that they contain relevant information.
  • Aesthetics is a branch of philosophy dealing with the nature of art, beauty, & taste, with the creation and appreciation of beauty. It is more scientifically defined as the study of sensory or sensori-emotional values, sometimes called judgments of sentiment and taste. More broadly, scholars in the field define aesthetics as "critical reflection on art, culture and nature.
 So what exactly are aesthetics? It pertains to how people judge you or your business when viewing your website. It means the perception of a user about you that is attained by what they see. In short, the opinion of whether or not your site looks good or not.

 Poor use of color combinations is among my top complaints when evaluating websites. If the site is hard on my eyes I simply don't want to be there. Additionally, poor graphics come in at a close second. Any graphics you use should be there to "enhance" the site, not just placed there because it feels like a good spot for one. It should help to tell the story or relay the applicable information.
  • Friendly Navigation is a little harder to define, but basically it means having a menu structure in place that is intuitive and allows users to get to any page/section from any other page/section.
 One of the very worse things you can do is confuse or frustrate a user by not implementing a good navigation system. If a user is trying to find some specific information or trying to get to a particular page, they won't hang around long if they can't get to where they want to go.

 One way of ensuring that your users have a menu constantly at their fingertips is to set the class to Position: Fixed so it won't move or scroll away when they move down the page. Or another approach is to have a menu system on the top and bottom of each page.

 But perhaps most importantly, make sure you don't have any dead links, meaning a link that doesn't go anywhere. You'll also want to make sure that each page has relevant information to that page's title. So if I go to a contact page, I should be able to see all of the different ways to contact that business, or if I go to the services page, I want to see what packages they offer and hopefully for how much.

 Beyond these basic four elements, you should always evaluate the content you are trying to deliver. Most of the time "less is actually more". Viewing a page or site that is really wordy won't help you get your message across. Each user spends approximately 10 seconds for any given page they visit, and even then is only scanning for what might interest them.

 You simply cannot expect a user to read through several paragraphs of information just to find what they really want to know. If you're wanting to display your services, then list them out, perhaps with a short blurb above or below it, but again, there's no need to go on and on about how you're better than the next guy or why a customer should choose you. Messages like that should probably be on the main page and then you still want to keep it at a very minimal character count.

 Lastly, do a self evaluation. If you're not happy with your site, why would you expect your users to be?

Tom M. Wiseman
Digital Dreams
http://www.digitaldrms.com