Friday, June 6, 2014

HTML5 Web form validations made easy Examples client-side validation without using JavaScript

HTML: HTML5 Form Validation Examples

HTML5 introduced several built-in form validation attributes that can be added to form elements to perform client-side validation without using JavaScript. Here are some commonly used validation attributes:
  1. Required: Specifies that an input field must be filled out before submitting the form.

    html
    <input type="text" required>
  2. Pattern: Allows you to specify a regular expression that the input value must match.

    html
    <input type="text" pattern="[A-Za-z]{3}">
  3. Min and Max: Sets the minimum and maximum values for numeric input fields.

    html
    <input type="number" min="1" max="100">
  4. Email: Validates that the input is a valid email address.

    html
    <input type="email">
  5. URL: Validates that the input is a valid URL.

    html
    <input type="url">
  6. Minlength and Maxlength: Specifies the minimum and maximum number of characters allowed in a text field.

    html
    <input type="text" minlength="5" maxlength="10">
  7. Pattern Error Message: Providing a custom error message for pattern validation.

    html
    <input type="text" pattern="[A-Za-z]{3}" title="Three letters only">
  8. Custom Error Message: Using the required attribute with a custom error message.

    html
    <input type="text" required="required" oninvalid="this.setCustomValidity('Custom error message')" oninput="setCustomValidity('')">

These attributes can be used in conjunction with <input>, <textarea>, <select>, and <button> elements to ensure input data meets specified criteria before submitting the form.




1. The 'required' attribute

The simplest change you can make to your forms is to mark a text input field as 'required':

Your Name: <input type="text" name="name" required>
 
Your Name:

This informs the (HTML5-aware) web browser that the field is to be considered mandatory
We have actually created our own valid/invalid formatting using CSS to override the browser default, but more on that later. That's why you may see something like the following in the example above:

HTML5 required example

Before you type anything into the box a red marker is shown. As soon as a single character has been entered this changes to a green marker to indicate that the input is 'valid'.
Using CSS you can place markers inside or alongside the input box, or simply use background colours and borders as some browsers do by default.
The required attribute can also be applied to checkboxes when you want them to be mandatory.

2. Different INPUT types

This is where HTML5 really gets interesting and more useful. Along with the text input type, there are now a host of other options, including email, url, number, tel, date and many others.

INPUT type="email"

Email Address: <input type="email" name="email" required placeholder="Enter a valid email address">

Note that for this example we've made use of another HTML5 attribute placeholder which lets us display a prompt or instructions inside the field - something that previously had to be implemented using messy onfocus and onblur JavaScript events.
The above code displays an input box as follows:
 
Email Address:

Again, different browsers implement this differently. In Opera it's sufficient to enter just *@* for the input to be accepted. In Safari, Chrome and Firefox you need to enter at least *@-.-. Obviously neither example is very limiting, but it will prevent people from entering completely wrong values, such as phone number, strings with multiple '@'s or spaces.
Here is how it appears in Safari (with our CSS formatting to show the (in)valid state):

HTML5 email required example

INPUT type="url"

Website: <input type="url" name="website" required>
Again, the input box appears as normal:
 
Website:

As mentioned above, we can improve on this by making use of the pattern attribute which accepts a JavaScript regular expression. So the code above becomes:
Website: <input type="url" name="website" required pattern="https?://.+">
Now our input box will only accept text starting with http:// or https:// and at least one additional character:
 
Website: starting with http

INPUT type="number" and type="range"

The number and range input types also accept parameters for min, max and step. In most cases you can leave out step as it defaults to 1.
Here you see an example including both a number input, typically displayed as a 'roller' and a range input displayed as a 'slider':

Age: <input type="number" size="6" name="age" min="18" max="99" value="21"><br> Satisfaction: <input type="range" size="2" name="satisfaction" min="1" max="5" value="3">
As with other HTML5 input types, browsers that don't recognise the new options will default to simple text inputs. For that reason it's a good idea to include a size for the input box.

(1-5)

The slider option is a bit bizarre in that no values are displayed, but may be useful for more 'analog' inputs. There are some bugs with the number input in that if you don't set a max value, clicking 'down' with the input blank will result in a very large number.
Here is how the two inputs are displayed in Safari:

HTML5 number and range example
and in Opera:
HTML5 number and range example

They are currently not supported in Firefox 4 Beta.
If you want to restrict the input of a text field to numbers without having the up/down arrows associated with the input box, you can always just set the input type to text and use a pattern of "\d+" (one or more numbers).

INPUT type="password"

We have a separate article with details on validating passwords using HTML5, including JavaScript code for customising the browser generated alert messages.

3. Other HTML5 INPUT types

Other HTML5 input types include:
  • color
  • date
  • datetime
  • datetime-local
  • month
  • search
  • tel
  • time
  • week
The search input will, in some browsers, change the styles to match the browser or operating system default search field format. You can see this demonstrated in the Search input above.
The tel input type is handy for the iPhone as it selects a different input keyboard. There is no pattern-matching set by default so you would have to implement that yourself using the pattern attribute to accept only certain characters.
The color input is meant to let you select a hex-code from a colour wheel - or similar - but as yet doesn't appear to have been implemented in the wild.
The other date- and time-related options do have an effect at least in Opera, with pop-up calendars and other devices appearing to assist with input. While it would be great to see something like this in every browser, for now you probably need to stick with the ubiquitous JavaScript plugins.

4. Styling valid/invalid inputs using CSS




While the code we're using is slightly more complicated, this should get you started:
input:required:invalid, input:focus:invalid { /* insert your own styles for invalid form input */ -moz-box-shadow: none; }
The first set of styles can be used to mark an input box as 'invalid', by adding an icon, colouring the text or borders or similar. It will apply to inputs that are required but empty, or to inputs that have a required format/pattern which hasn't yet been met.
The -moz-box-shadow style is there just to prevent Firefox 4 Beta from adding it's default red border.
For inputs that are both required and 'valid' you can use the following:
input:required:valid { /* insert your own styles for valid form input */ }
Some of the articles below, particularly the first two, provide other style/scripting options and solutions for supporting older browsers.


In tandem with the new input types and attributes provided by HTML5, CSS3 gives us some new pseudo-classes we can use to provide visual clues to the user as to which form fields are required, which are optional, and which contain validation errors.
Required fields can use the :required pseudo-class:
input:required {
    background:hsl(180, 50%, 90%);
    border:1px solid #999;
}
Optional fields can use the :optional pseudo-class:
input:optional {
    background:hsl(300, 50%, 90%);
    border:1px dotted hsl(180, 50%, 90%);
}
The success or failure of form validation can be signified to the user through the use of the :valid, :invalid, :in-range, and :out-of-range pseudo-classes:
input:valid,
input:in-range {
    background:hsl(120, 50%, 90%);
    border-color:hsl(120, 50%, 50%);
}

input:invalid,
input:out-of-range {
    border-color:hsl(0, 50%, 50%);
    background:hsl(0, 50%, 90%);
}

5. Sample styling using images and sprites

As shown above, once you've added HTML5 attributes to your form elements, they can be easily styled using CSS so that each input field is clearly marked as valid or invalid.
<style type="text/css"> input:required:invalid, input:focus:invalid { background-image: url(/images/invalid.png); background-position: right top; background-repeat: no-repeat; } input:required:valid { background-image: url(/images/valid.png); background-position: right top; background-repeat: no-repeat; } </style>
Here you can see the above styles applied to a required input field:

Your Name: (required)

This solution is still more complicated than it needs to be as it requires two extra images to be loaded. Fortunately, we can assume that all browsers supporting HTML5 form validation techniques will also support images being replaced in the CSS by 'Base64 encoded datasets'.
Using a service such as Spritebaker or other techniques, the above style settings become:
<style type="text/css"> input:required:invalid, input:focus:invalid { background-image: url(data:image/png;base64    background-position: right top; background-repeat: no-repeat; -moz-box-shadow: none; } input:required:valid { background-image: url(data:image/png;base64,=); background-position: right top; background-repeat: no-repeat; } </style>
The above code can now be copied directly to your CSS style sheet. There's no need to copy any images and, especially if your style-sheets are gzip-compressed, there will be next to no impact on load times. In a few minutes you could have your whole website updated.
For the browser-impaired, this is how the required input field will appear in Safari with either the image or the Data URI backgrounds:
HTML5 required example 2
The same styling can be extended to textarea elements, but won't work for checkboxes, select elements, etc. For those you might want to place the valid/invalid markers alongside the element or format the input elements themselves using borders, background colours, etc.

6. Fallback for the placeholder attribute

The following JavaScript, placed or included at the end of the page, should enable support for the placeholder attribute in INPUT fields at least for Internet Explorer 8+, Firefox and Opera:
<script type="text/javascript"> // ref: http://diveintohtml5.org/detect.html function supports_input_placeholder() { var i = document.createElement('input'); return 'placeholder' in i; } if(!supports_input_placeholder()) { var fields = document.getElementsByTagName('INPUT'); for(var i=0; i < fields.length; i++) { if(fields[i].hasAttribute('placeholder')) { fields[i].defaultValue = fields[i].getAttribute('placeholder'); fields[i].onfocus = function() { if(this.value == this.defaultValue) this.value = ''; } fields[i].onblur = function() { if(this.value == '') this.value = this.defaultValue; } } } } </script>

7. INPUT patterns for different data types

URL input pattern:

input type="url" pattern="https?://.+"

IPv4 Address input pattern:

input type="text" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

Date input pattern (dd/mm/yyyy or mm/dd/yyyy):

input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}"

Price input pattern:

input type="text" pattern="\d+(\.\d{2})?"

Latitude/Longitude input pattern:

input type="text" pattern="-?\d{1,3}\.\d+"

---------------------------------------------------->>>>>>
<input type="url">
<input type="email">
<input type="password">
<input name="q" placeholder="Go to a Website">
<input type="number"       min="0"       max="10"       step="2"       value="6">

<input type="date">:
<input type="datetime">:
<input type="month">:
<input type="week">:
<input type="time">:
<input  type="search">

<input type="color">,
<input id="q" required>
<input id="q" autofocus>

---------------------------------------------------->>>>>>

HTML5 Simple and powerful responsive web templates

http://www.html5webtemplates.co.uk/templates.html


Source http://www.the-art-of-web.com/html/html5-form-validation/
            http://html5pattern.com/Names


BIT UCSC UoM, BSc, HND Students Projects and Guidance
 
Call + 94 777 33 7279
Email ITClassSL@gmail.com

 

Monday, June 2, 2014

How php session handling and managing

Sessions


A session begins when a visiting client somehow identifies itself to the web server. The web server assigns the client a unique session id, which the client uses to re-identify itself as it moves from page to page on the website. Most of the time, these unique ids are stored in session cookies that expire after the client hasn't interacted with the server for some amount of time. The amount of time varies depending on the web application. For example, an online investment site might have very short sessions, so that if a user leaves her computer without logging out, another user who sits down at the same computer several minutes later cannot continue with the first user's session.

Configuring Sessions

In PHP, session management is configured in the php.ini file. To have a user's session start as soon as the user visits the website, the session.auto_start flag must be set to 1.
The session length is also set in the php.ini file with the session.gc_maxlifetime variable. The default value is 1440 seconds (24 minutes).

Session Functions

The following table shows the most common session functions.
FunctionExplanation
session_start()Starts new session if one does not exist. Continues current session if one exists.
session_unset()Unsets all session variables.
session_destroy()Kills session.

Source http://www.learnphp-tutorial.com/session-control-and-cookies.cfm

========================================================================

Securing PHP User Authentication, Login, and Sessions

Many, if not all, of you have had to deal with creating a secure site login at some point in time. Although there are numerous articles written on the subject it is painstakingly difficult to find useful information from a single source. For this reason I will be discussing various techniques I have used or come across in the past for increasing session security to hinder both session hijacking and brute force password cracking using Rainbow tables or online tools such as GData. I use the word hinder due to the fact no foolproof methods exist for preventing session hijacking or brute force cracking, merely increasing degrees of difficulty. Choose a method wisely based on your site’s current or anticipated traffic, security concerns, and intended site usage. The following examples have been coded using PHP and MySQL. I more than willingly accept comments, suggestions, critiques, and code samples from readers like you as they benefit the community on the whole.

Update: Security Concerns with Hashing Algorithms

There are some inherent security considerations to take into account when using very fast hashing algorithms such as SHA or MD5. Modern day, multi-processor computers and GPUs can quickly brute-force passwords that aren’t encrypted with a very slow, secure algorithm. For these reasons, it is recommended you do not use these and instead use bcrypt encryption or sha-256/512 with key stretching. In the near future there will be a post containing this updated method for secure authentication.


Source http://blackbe.lt/php-secure-sessions/




========================================================================

Session Best Practices


Use SSL when authenticating users or performing sensitive operations.
One of the comments to the SO answer points out that you have to use HTTPS for every page on the site, or a hacker can easily steal the session ID the first time a non-HTTPS request is made. Does anyone have any thoughts on this?

Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish.
What's the best way to regenerate the session ID? Actual code would be helpful for this. Thanks.

Have sessions time out
How do you make a session time out?

Don't use register globals
What is the problem with using registered globals? I don't get the problem with this at all.

Store authentication details on the server. That is, don't send details such as username in the cookie.
This point is pretty straightforward and obvious.

Check the $_SERVER['HTTP_USER_AGENT']. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here).
A lot of the comments to this answer seem to be related to checking the user agent string. Maybe it's best to just avoid this check. Any thoughts?

Lock down access to the sessions on the file system or use custom session handling
I don't understand this point at all. How do you lock down the session on the file system. Also, how would you go about creating a custom session? Would it just be an array of data stored in the DB?

For sensitive operations consider requiring logged in users to provide their authenication details again
This is a good point, but I think it's important to consider the balance necessary for protecting the user without annoying them too much.

Source http://www.larryullman.com/forums/index.php?/topic/2916-secure-session-best-practices/ 

========================================================================
  1. What is a session?
  2. How do I use a Session?
  3. How do sessions work?
  4. How do I change the value of a session variable?
  5. Can I destroy a session variable?
  6. What should I do to destroy a whole session?
  7. Can I store an array in a session?
  8. Can I store an object in a session?
  9. Can I store an file pointer in a session?
  10. Can I store a function in a session?
  11. Can I store an image in a session?
  12. How are sessions stored?
  13. Storing sessions with SQLite
  14. When do sessions expire?
  15. How can I send headers then start a session?
  16. How can I check if a session is started?
  17. How can I check if a session uses a cookie or query string
  18. Session Configuration with php.ini
  19. Session security
Learn more above from http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html



To complete your PHP/mySQL projects

HND, BSc - SLIIT/NIBM/APIIT/IIT/BCAS/ICBT/ACBT, BIT - [university of colombo UCSC / university of moratuwa UoM]

 

Call +94 777 33 72 79           Email ITClassSL@gmail.com