Home > Categories > HTML
Page 1

Creating a simple to-do application – Part 4

Introduction

This week in part 4 of creating our simple to-do application we’ll be learning how to send email notifications/reminders. To do this we’ll be using the PHP mail method and learning how to schedule repeatable tasks on Linux using cron. The equivalent process for Windows is the task scheduler and it is pretty self explanatory. WordPress has what it calls the wp-cron alternative, but it’s use is limited as it requires someone to actually use the site.

Cron

Cron is the Unix/Linux schedule process, it allows users to configure tasks that are executed at defined intervals. It’s not exactly considered to be particularly user friendly, so many hosting providers have a simplified UI to help set it up. In any event, it is still beneficial to know the basics.

Cron jobs are specified in the ‘crontab’ file (typically in the /etc folder) Crontab is short for cron table, and as the name suggests it is a series of columns that determine when and what is run, split up in to tasks on each new line of the file. Each column has a specific time related function, with the last being the actual file that is executed. The column order is as follows:

Minutes (0 – 59) Hours (0 – 23) Day of month (1 – 31) Month (1 – 12) Day of week (0 – 6) File or command

You can specify any combination of the above columns, disabling columns is by way of the * character. This configuration method can lead to some confusing schedules being created. You can specify that any Monday, that is the 1st of the month at 11am execute some task. It would look something like this:

* 11 1 * 1 task.php

Overall it’s quiet a powerful system that you can configure to do almost anything. There are a few things to note, don’t schedule a task that takes 5 minutes to execute every minute. Cron will execute this and you will end up with duplicate scripts taking up resources and potentially causing issues.

PHP mail

PHP has a built in email function that is incredible easy to use. It uses the default SMTP server details in your php.ini configuration to send emails. Generally if you’re running in a hosted server this will be configured, if it’s not or if you want to use a different server you can use the ini_set function to update your configuration. The ini_set command would look something like this:

ini_set("SMTP", "smtpserver.yourdomain.com");

To actually send an email, you have to provide the following information:

The “to” address The subject The message Additional headers Additional parameters

The “to” address can be a simple one line “you@domain.com” or either a csv of email addresses. You can also specify the name of the person in this field as follows:

Bob Bobberson <bobby@bobberson.com>

Another quirk about the mail function is that the message body must be split on to multiple lines of no more than 70 characters. To indicate a new line you need to use the \r\n (CRLF) characters.

There is only one header that must be sent and that is the “from” header. You can also specify the “reply-to” or CC and BCC headers. The CC and BCC values have the same format as the “to” field. A full email would look something like this:

$from = "To Do Application <to-do@domain.com>"; $to = "Bob Bobberson <bobby@bobberson.com>"; $subject = "How to send an email in PHP"; $message = "Read this! Sending an email in PHP is really easy"; $headers = "From: To Do Application "; $headers .= "Bcc: Another attendee "; $headers .= 'Reply-To: ' . $from; $headers .= 'Return-Path: ' . $from; mail($to, $subject, $message, $headers);

I should also note, that if you are planning on sending lots of emails there are better alternatives out there that will queue emails and perform better in general. The mail function is not designed to scale quickly or well, however for once off emails it is sufficient

Building our script

So now we know how we’re going to schedule our emails and we also know how we’re going to send them, next up is what are we going to send? To do this it’s back to our MySQL database and a simple query. Here we’re going to do a simple select from our ‘tasks’ table where the ‘task_date’ is between 15 and 20 minutes from now. To do that we use the MySQL ADDDATE function.

SELECT `task_id`, `user_firstname`, `user_surname`, `user_email`, `task_name`, `task_priority`, `task_color`, `task_description`, `task_attendees`, `task_date` FROM `tasks` AS t INNER JOIN `users` AS u ON u.user_id = t.user_id WHERE `task_date` >= ADDDATE(NOW(), INTERVAL 15 MINUTE) AND `task_date`...
more →
Arjun says: Thanks for giving this list. I spent one hour time for this article, It is very useful info for me..

Creating a simple jQuery plugin for Pinterest

Introduction

Plugins play a great part in the success of jQuery. There are hundreds of them out there, and having the ability to create your own is a great skill to have. With all of the interest in Pinterest (no pun intended), I thought it would be a good idea to do up a quick and simple Pinterest sharing plugin for jQuery.

Getting started

First we need to grab the jQuery plugin boilerplate

(function( $ ) { $.fn.pinterest = function(options) { var settings = $.extend( { }, options); return this.each(function() { }); }; })( jQuery );

This boilerplate provides us with the ability to specify default configuration values (settings) and ensures that the infamous jQuery chaining ability is maintained (the return this.each). I’m going to take advantage of the default configuration values by specifying the default Pinterest image we’ll be using. This can be overridden when initializing the plugin by specifying the url to the preferred image.

Default image

Custom image

(function( $ ) { $.fn.pinterest = function(options) { var settings = $.extend( { 'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png' }, options); return this.each(function() { }); }; })( jQuery ); $(document).on('ready', function(){ $('img#share').pinterest({ button: 'pinterest-alt.png'}); });

Now that we have a basic framework done, let’s start adding some functionality. We need to update the this.each function to initialize each image and add some events for us. I’ve chosen to have the icon hover over the image being shared. To do this, I need to wrap the image in a span element that positioned ‘relative’, I then need to append the share image and position it absolutely. I’m going with the bottom right, but feel free to have a play

(function( $ ) { $.fn.pinterest = function(options) { var settings = $.extend( { 'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png' }, options); return this.each(function() { img = $(this); img.wrap('<span class="pin-it" style="position: relative;" />'); img.parent('span.pin-it').append('<img...
more →
Sean Meyer says: That's pretty cool. I've only ever done one jQuery plugin myself and that was just something simple to see if I could do it. I...

Adding a simple authentication using PHP require and includes

Introduction

Please note that this tutorial has now been superseded by a later, more in-depth tutorial available here

Continuing on with our to-do application, in this weeks snippet we’re going to be using PHP’s require_once function. The require_once function is similar to the require function, in that it will execute and include any php code with the calling file but with one vital difference. It will only execute once. This is important for us in this tutorial as we are going to use it to validate our user.

There are a few things to note first, since this is a short tutorial I will be doing something that is not a good idea in a production application. I will be storing the logged in state in the $_SESSION variable, this is only temporary as next week we will be updating it to store it in a MySQL database. We will also be storing in the database additional information such as the source IP address and a timestamp to mitigate against session hi-jacking.

Getting started

First we will need to convert our existing index.html file to a php file. To do this, simply change the extension to ‘.php’ and open the file in your text editor. We will now also create a new php file called ‘authenticate.php’ and save it in the same folder as our new index.php.

Now inside our index file, we are going to add the following php code to the very top of the file.

<?php require_once('authenticate.php'); ?>

This means that as soon as the file is executed, it will read and execute our authenticate.php file. The contents of the authenticate file is also pretty straight forward for now. We’re going to ensure our session has been started (session_start), and then check to see if the $_SESSION variable contains our authenticated flag. If it doesn’t exist or is not set to ‘true’ we will re-direct the user to our 3rd new page login.php. To perform the re-direct we are going to update the header Location value to point to our login.php file.

By also adding the above code to our submit.php, we can also ensure that only authenticated users can add tasks.

<?php session_start(); if(empty($_SESSION["authenticated"]) || $_SESSION["authenticated"] != 'true') { header('Location: login.php'); } ?>

In the scenario where we have already logged in, the index.php file will continue to execute as normal and we shall see our form and table as usual.

Logging in

Next up, we are going to create our login page. For now, it will be just a simple username and password form that uses POST to send the provided details to itself.

<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Creating a simple to-do application - Part 1</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="page"> <!-- [banner] --> <header id="banner"> <hgroup> <h1>Login</h1> </hgroup> </header> <!-- [content] --> <section id="content"> <form id="login" method="post"> <label for="username">Username:</label>...
more →
Ccornutt says: By the way, for anyone reading this article that didn't get it - please, please *please* do not hard-code passwords into your...

Creating a simple to-do application – Part 2

Introduction

Continuing on from last weeks tutorial (Creating a simple to-do application – Part 1) and the short snippet (Turning a form element into JSON and submiting it via jQuery ), this week we’ll be writing a PHP page to accept and process the form submit and return a JSON response.

Installing PHP on your web server

There are several ways to install PHP to your web server, but each is dependent on what web server you are running. The two main ones I will deal with are Microsoft’s Internet Information Services (IIS) and Apache. IIS will only run on Windows, but Apache will run on either Windows, OSX or your favorite Linux Distro (e.g Ubuntu). For each operating system there are several easy to use packages that will install and configure both the web server and php.

Apache

The easiest package for Apache I find is XAMPP, it provides installers for all of the major platforms and is very easy to use. You can download it directly from the site based on your operating system and follow their install guides.

Linux Windows OSX

The XAMPP site includes details on where to put your files and how to create alias folders. These topics and more are covered in the install guides above.

IIS

IIS actually comes free with Windows, it generally isn’t installed by default but you can add it in the “Add/Remove Programs” section of the Control Panel under “Turn On/Off Windows Features” (For a detailed step by step guide, click here). The easiest way to install PHP is to download the Microsoft Web Platform Installer. It will offer you a range of programs to install, everything from PHP and WordPress to various e-commerce platforms. All you do is pick the applications you want, and they will automatically be installed!

By default web files go in the following folder C:\inetpub\wwwroot, you can however create “Virtual Folders” that point anywhere you want. To continue this tutorial, please save the index.html page in to wwwroot or create a virtual folder

Getting started

Assuming you’ve gotten your web server running and PHP configured, let’s get started! (If you are having trouble, please feel free to ask in the comments section below and I will help as best I can).

First we’ll create our submit.php file (in the same folder as our index.html file) and then using the PHP global variable $_POST we will retrieve the form values we have submitted using jQuery. PHP code is always wrapped in “<?php ?>” tags, anything outside of these tags is rendered as normal (like HTML).

<?php $name = $_POST["new-task-name"]; $date = $_POST["new-task-date"]; $desc = $_POST["new-task-desc"]; $email = $_POST["new-task-email"]; $priority = $_POST["new-task-priority"]; $color = $_POST["new-task-color"]; ?>

We are using the $_POST variable instead of the $_GET because we specified our jQuery submit method as ‘POST’, this can be easily changed if you prefer to use ‘GET’

Now that we have our form values, we’ll have to provide some basic validation on them. We know that we need a name, the date and priority values, but we also know that we can specify optional values and in the case of the email field a comma separated list. First we’ll make sure our required values, do in fact have values and that they are formatted correctly.

Firstly, we’re going to specify some default values and then update the variables after we have confirmed that each of the form values has been provided. We can do this using the empty function.

<?php $name = null; $date = date('c'); $desc = null; $email = null; $priority = 2; $color = '#ffffff'; if (!empty($_POST["new-task-name"])) $name = $_POST["new-task-name"]; if (!empty($_POST["new-task-date"])) $date = $_POST["new-task-date"]; if (!empty($_POST["new-task-desc"])) $desc = $_POST["new-task-desc"]; if (!empty($_POST["new-task-email"])) $email = $_POST["new-task-email"]; if (!empty($_POST["new-task-priority"])) $priority = $_POST["new-task-priority"]; if (!empty($_POST["new-task-color"])) $color = $_POST["new-task-color"];...
more →
Jonny Schnittger says: Other than the type casting here, security will be introduced as part of a later tutorial. I'm trying to break the various topics...

Creating a simple to-do application – Part 1

Introduction

This is the first part of a series of tutorials that aim at to cover all aspects of web development. Each part in this series will build on the previous one, covering topics such as:

HTML5 CSS3 jQuery

We’ll also be covering slightly more advanced topics such as:

AJAX PHP MySQL Email Security/Authentication

Where required I will go into the basics of getting a development environment installed and configured. I will also cover basic design methodologies and best practice.

The Application

To start off we’re going to create a very basic to-do list application, every week we will add new features to it or extend existing ones. These following features will be implemented:

Save tasks and general information to a MySQL database Use jQuery to perform AJAX post-backs Add/Edit/Remove a task and save it using AJAX Refresh just the task list using AJAX Mark tasks as completed using AJAX Automatically sort tasks based on due date and priority Automatically email a reminder to the user (or attendees) of an up-coming task Use CSS animations to show activities Use CSS and jQuery to create a responsive design and layout that works on multiple platforms

Once this series is completed you should have a fully functional, database driven, responsive to-do application.

This week we’re going to get a basic wire-frame layout for our screen and start adding some basic styling.

Getting started

To start, we have to define the attributes of our task. This list isn’t final, but it’s a start:

Task name (string 250 characters, required) Date (DateTime, required) Priority (numeric 1-5, required) Color (string, hex or rgb value) Description (string, 1000 characters) Attendees (list of email addresses)

As you can see I’ve also specified the data type or a description for each property, this gives me a better idea of what requirements I have. It tells me not only what data type (number, string, etc…) I will need to store it as in the database, but also tells me what controls I can use.

The normal way of getting information in a web page is the using the <form> and <input> elements. In HTML5 several new input types and attributes have been added to make them more useful. Input elements have gained a new attribute ‘required’ and the following new types have been added:

datetime number color email

These new input types are pretty self explanatory, but their implementation is limited across all browsers. Specifically IE and Firefox are poor, but even Chrome doesn’t support all of them. The best browser for these turns out to be Opera funnily enough (as such all screenshots are from Opera). We’re going to use them, but in certain browsers we’ll have to augment their functionality using jQuery plugins to make the experience consistent (This will be covered in a later tutorial).

Another new feature added in HTML5 is the automatic validation of an inputs value depending on it’s type. For example the new number type must have a numeric value. Using attributes it is possible to set minimum and maximum values, including the step (or how much the value increases in one go)

<input type="number" required min="1" max="5" step="1" value="2">

The form

Now that we know what input types we have available to us we can decide how best to use them.

<form id="add-new-task"> <input id="new-task-name" name="new-task-name" type="text" required> <input id="new-task-date" name="new-task-date" type="datetime" required> <input id="new-task-priority" name="new-task-priority" type="number" required min="1" max="5" step="1" value="2"> <input id="new-task-color" name="new-task-color" type="color"> <input id="new-task-desc" name="new-task-desc" type="text"> <input id="new-task-email" name="new-task-email" type="email" multiple> <input type="submit" value="Add new"> </form>

As you can see I’ve marked the name, date and priority inputs as required, but I’ve also set the multiple attribute on the email input. This attribute tells the browser that there can be more than one email address in input. These emails will be separated by comma.

Now lets apply a little structure to our form and add label elements and split out the inputs on to separate rows

<form id="add-new-task"> <label for="new-task-name">Name:</label> <input id="new-task-name"...
more →
Jonny Schnittger says: I'll actually be introducing jQuery plugins in an upcoming tutorial as a way of making the UI behavior consistent. I'm focusing...

A Continuous CSS3 Animation

Introduction

Static headers with boring backgrounds are everywhere… why don’t you try and spice yours up with a simple CSS animation?

I’d like you to meet Bob, he’s my friendly static image and he’d really like to wave hello to you!

Let’s give him the chance.

First up we’ll need to do a quick operation and temporarily remove his arm (Sorry Bob!)

Then we’re going to rotate his arm (very gently) by 45 degrees.

Now we can start re-assemble him using some simple HTML

<div class="logo"> <div class="arm"></div> <img src="body.png" /> </div>

We’re not quiet there yet, we’ll have to position his arm back in place

div.logo { position: relative; } div.logo div.arm { position: absolute; width: 138px; height: 138px; background: url('arm.png') top left no-repeat; top: 20px; left: 150px; z-index: -1; }

That’s a little better, now that’s he’s back in one piece let’s get him waving!

First we’ll need to specify our animation. We do that using the CSS animation properties. For this example we’re going to call our animation wave. We’ll define it in a minute, but first we have to update our div.logo div.arm class to the following.

div.logo div.arm { position: absolute; width: 138px; height: 138px; background: url('arm.png') top left no-repeat; top: 20px; left: 150px; z-index: -1; -webkit-animation: wave 2s ease-in-out infinite; -moz-animation: wave 2s ease-in-out infinite; animation: wave 2s ease-in-out infinite; }

As you can see we have given the name of our animation “wave”, a duration of 2 seconds, the ease-in-out timing function, and we’ve said to repeat it for infinity.

Now we have to define our actual wave animation, we do that using the @keyframes rule. Here we have to deal with browser support issues and define -webkit- and -moz- versions of the rule.

@-webkit-keyframes wave { 0% { -webkit-transform: rotate(0deg) translate(0px); transform: rotate(0deg) translate(0px); } 50% { -webkit-transform: rotate(30deg) translate(50px); transform: rotate(30deg) translate(50px);...
more →
Kizi friv says: Your article is intelligent, literate and compelling as way as i am involved. I've enjoyed reading and reviewing your...

The humble table

Introduction

I’m going to tell you a story, its about love, death and re-birth… Or something

In the beginning there was a young html element called <table>. He had one purpose in life, to display data and life was good. But before long though he had been corrupted, his masters used him to define layout and structure. Things he was not originally designed to do, and so began the dark ages of web design. Then one day, there came a young knight called CSS, and with him he brought light to designers everywhere. He was so beloved, the designers made him their King. Under his rule (selectors… sorry bad joke) the web flourished, sites became less structured, better looking and more responsive.

He was so well loved, people tried to make everything in his image. They found that they could display data in grid shaped patterns using lists and the all-powerful code that CSS had bestowed up on them.

But all was not well in the Kingdom of Web, the poor forgotten element table looked on. Increasingly spurned, he grew jealous. He knew that with his one purpose in life, he could display data better than any other magical element. But how could he regain his once strong foothold in the land of websites?

He, being a simple yet good element, prayed to the Gods of Standards and they heard him. They rebuilt and tweaked him, they made him streamlined and functional. Once they were done, they set him out into the world with a renewed purpose. Capable of showing data better than ever before, he approached the King, who now having moved on in years and being more mature recognized the tables usefulness and decided to re-instate the lowly table back in to his rightful place.

And the moral of the story is… use tables to show tabular data… don’t try and invent the wheel!

I also apologize for desecrating the HTML logo with my terrible drawing skills

On with the tutorial!

HTML5 has brought in several changes to the table element. Gone are the majority of table attributes, width/height, cellspacing/cellpadding and border are all gone. The look and feel should now be controlled by CSS (as it should be). In the above story, I said not to use tables for layout… people are still going to do this, they do provide structure and layout quiet easily. To help with this, it is now recommended that the attribute role should be specified with a value of “presentation”. This is to help site scrapers/aggregators know what content to ignore.

<table role="presentation"></table>

The following elements are for use within the table element:

caption colgroup col tbody thead tfoot tr td th

Each has a specific and well defined function. They also have to be used in specific ways and orders.

The <caption> element must be the 1st child element of a table, its purpose is to describe what the table is being used for. It appears on top of the table data.

<table id="table-1"> <caption>Tables are for displaying tabular data, not layout!</caption> </table>

Next up is the <colgroup> element, it’s used for grouping columns together. By specifying the span attribute you can tell the browser to apply a style to the columns (represented by the <col> element) in that group. Both the <colgroup> and <col> elements can use the span attribute, but they cannot be used at the same. It’s on one or the other but not both.

<table id="table-1"> <caption>Tables are for displaying tabular data, not layout!</caption> <colgroup> <col /> <col /> <col /> <col /> <col /> <col /> </colgroup> </table>

The <colgroup> and <col> elements are used for presentation, to actually define a tables columns you use the <thead> element. To define the columns you specify a single <tr> element and then use the <th> element.

<table id="table-1"> <caption>Tables are for displaying tabular data, not layout!</caption> <colgroup> <col /> <col /> <col /> <col /> <col /> <col /> </colgroup> <thead> <tr> <th scope="col"></th> <th scope="col">Column 1</th> <th scope="col">Column...
more →