Friday, December 12, 2014

What is htaccess?


Using this ".htaccess" file we can control "php.ini" and "httpd.conf" file.

For php.ini:

for register globals Enter "php_flag register_globals on" in that file and place it inside the context folder where you are running the php files. Now this is set to globals throughout the files present inside that context folder. This is boolean so we are giving like "php_flag". if it is the value we have to give like "php_value"

For example : [php_value sendmail_from "dineshsdk85@gmail.com"] we have to give like this for the values.

PHP Form Hijacking. How to prevent form hijacking in PHP?


Following things can be done for preventing your PHP Form from Hijacking

1. Make register_globals to off to prevent Form Injection with malicious data.

2. Make Error_reporting to E_ALL so that all variables will be initialized before using them.

3. Make practice of using htmlentities(), strip_tags(), utf8_decode() and addslashes() for filtering malicious data in php

4. Make practice of using mysql_escape_string() in mysql.

5. User Input Sanitization-Never trust web user submitted data. Follow good clieint side data validation practices with regular expressions before submitting data to the server.

6. Form Submission Key Validation: A singleton method can be used to generate a Session form key & validating form being submitted for the same value against hidden form key params.

Thursday, June 21, 2012

How to increase PHPs execution time for processing large set of records?

1. In php.ini file change the below line values it will change the maximum execution time.

max_execution_time 30

2. To increase the execution time runtime we can use the ini_set() function.
e.g.
ini_set('max_execution_time' '-1'); - it sets maximum execution time to infinity.

What is CAPTCHA?

CAPTCHA stands for Completely Automated Public Turing Test to tell Computers and Humans Apart.

To prevent spammers from using bots to automatically fill out forms, CAPTCHA code generate an image containing distorted images of a string of numbers and letters. Computers cannot determine what the numbers and letters are from the image but humans can determine the string of numbers and letters. By entering the numbers and letters from the image in the validation field the application can be fairly assured that there is a human client using it.

What are the different methods to optimize the MySQL query?

It does not depend upon single entity. In order to optimize you have to consider many things:

1. Make sure table has primary key.

2. If there is any field which is used more frequently for searching then INDEX it.

3. Check the order of join condition.

4. In "Select" statement "where" condition should have indexed column.

5. Use "Limit" clause to fetch required amount of records from the database.

6. Use "count()" instead of "*" if you want to know the number of records fetched from the DB.

How to prevent form Hijacking in PHP?

Following the below steps can help prevent your PHP Form from getting Hijacked:

1. Make "register_globals" set to "Off" to prevent Form Injection with malicious data.

2. Make "Error_reporting" set to "E_ALL" so that all variables will be initialized before being used.

3. Make practice of using htmlentities(), strip_tags() and addslashes() to filter out malicious data entered.

4. Make practice of using mysql_escape_string() in mysql.

5. User Input Sanitization: Never trust web user submitted data. Follow good client side data validation practices with regular expressions before submitting data to the server.

Store Image in MySQL

We can use the "blob" datatype for storing the the image into the table.

However, the best way to store images into MySQL is to store the location of the image as a character string.

Friday, February 11, 2011

About ExpressionEngine [EE]

Expression Engine is a very powerful content management system that can be used to manage your website and blog. All you have to do is add EE tags into the portions of your pages where you want your posts / content to appear. It has all the inbuilt basic features that is required to create a website. However, for more complex implementation you would need to buy / get free add-ons or hack the code to suit your needs.

Fetching and displaying the data is an easy part. Challenge comes in when you want to display it in a more creative way.

Like at one such instance, we needed a feature to add ratings for an article and at the same time add customer's review. To achieve this we simply made changes to the add-on's class file, added a field to the ratings table in the database to store the reviews as well as the score, since we wanted to display the customers review for the article along with the rating.

Second, displaying breadcrumbs in a customized way. Though there are add-ons available for the same, but add-on's displayed the breadcrumbs based on the query string. So, we had to modify the class file to suit our requirements.

Third, in certain cases there were limitations to using EE tags, particularly nested "weblog" tags. To overcome such situations we have used queries instead to fetch the required data for further processing in the inner loops.


Conclusion

So, unlike learning any new application especially content management systems, learning EE was comparatively less painful. The more you work on it, the more you discover about its potential. Be it a usual CMS site, Shopping Carts, Blogs etc. EE

How to get next auto increment value of a primary key field in MySql?

<?php
function mysql_next_id($table) {
$result = mysql_query('SHOW TABLE STATUS LIKE "'.$table.'"');
$rows = mysql_fetch_assoc($result);
return $rows['auto_increment'];
}
?>

Programmers try other ways to retrieve the next auto-generated id and fail to get correct value.

Example:
Most of the programmers try to get the MAX(id)+1 (or sort the table in decending order and get the first id) but this will not to work when you delete the last record.

There is a possibility that other users have entered record in the meantime, in this case the value that you have retrieved would be incorrect. You may use LOCK TABLES to prevent such a case.

However, the best thing is to avoid such logics.

Wednesday, November 18, 2009

What are the various methods to pass data from one web page to another web page ?

Below are the ways to pass data acros the pages:

1.POST
2.GET
3.SESSION
4.COOKIES
5.QUERY STRING

What is a Zend Engine?

The Zend Engine is an open source scripting engine (a Virtual Machine), commonly known for the important role it plays in the web automation language PHP.

The current version of the virtual machine is The Zend Engine II and is at the heart of PHP 5.

What are the types of Storage Engines MySQL supports?

MySQL supports several storage engines that act as handlers for different table types. MySQL storage engines include both those that handle transaction-safe tables and those that handle nontransaction-safe tables.

To determine which storage engines your server supports by using the SHOW ENGINES statement. The value in the Support column indicates whether an engine can be used. A value of YES, NO, or DEFAULT indicates that an engine is available, not available, or avaiable and current set as the default storage engine.

MySQL 5.1 supported storage engines

1. MyISAM ? The default MySQL storage engine and the one that is used the most in Web, data warehousing, and other application environments. MyISAM is supported in all MySQL configurations, and is the default storage engine unless you have configured MySQL to use a different one by default.

2. InnoDB ? A transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data. InnoDB row-level locking (without escalation to coarser granularity locks) and Oracle-style consistent nonlocking reads increase multi-user concurrency and performance. InnoDB stores user data in clustered indexes to reduce I/O for common queries based on primary keys. To maintain data integrity, InnoDB also supports FOREIGN KEY referential-integrity constraints.

3. Memory ? Stores all data in RAM for extremely fast access in environments that require quick lookups of reference and other like data. This engine was formerly known as the HEAP engine.

4. Merge ? Allows a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as one object. Good for VLDB environments such as data warehousing.

5. Archive ? Provides the perfect solution for storing and retrieving large amounts of seldom-referenced historical, archived, or security audit information.

6. Federated ? Offers the ability to link separate MySQL servers to create one logical database from many physical servers. Very good for distributed or data mart environments.

7. NDBCLUSTER (also known as NDB) ? This clustered database engine is particularly suited for applications that require the highest possible degree of uptime and availability.

8. CSV ? The CSV storage engine stores data in text files using comma-separated values format. You can use the CSV engine to easily exchange data between other software and applications that can import and export in CSV format.

9. Blackhole ? The Blackhole storage engine accepts but does not store data and retrievals always return an empty set. The functionality can be used in distributed database design where data is automatically replicated, but not stored locally.

10. Example ? The Example storage engine is ?stub? engine that does nothing. You can create tables with this engine, but no data can be stored in them or retrieved from them. The purpose of this engine is to serve as an example in the MySQL source code that illustrates how to begin writing new storage engines. As such, it is primarily of interest to developers.

What type of inheritance that php supports?

PHP support the Multilevel inheritance Not a multiple inheritance.

For Example:

class A{

function hello();
}

// This is possible.
class B extends A{

function helloB();
}

// This is not possible, IT gives the fatal error.
class C extends A{

function helloC();
}

Where Is Session Data Stored?

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
The most significant differences between the two are that cookies are stored on the client, while the session data is stored on the server. As a result, sessions are more secure than cookies (no information is being sent back and forth between the client and the server) and sessions work even when the user has disabled cookies in their browser. Cookies, on the other hand, can be used to track information even from one session to another by setting it's time( ) parameter

The session.save_path setting specifies the directory name for session data.

What is the purpose of ob_start() ?

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

What are new features that are in added in PHP5?

Following are new features added in PHP5

1. PHP 5 introduces the Standard PHP Library (SPL) which provides a number of ready-made classes and interfaces.
2. Access Modifiers are added in PHP5
3. PHP5 has built-in exception classes that makes it very easy to create your own customized exceptions through inheritance.
4. PHP 5 introduces the mysqli (MySQL Improved) extension with support for the features of MySQL databases versions 4.1 and higher. So use of prepare statements are allowed
5. PHP5 comes with PDO which is a common interface for different database systems is only made possible by the new object model.
6. SQLite is a database engine incorporated in php5 which can be used to develope faster leaner and more versatile applications.
7. In PHP 5 all Extensible Markup Language (XML) support is provided by the libxml2 XML toolkit.
8. The reflection classes included in PHP 5 provide ways to introspect objects and reverse engineer code.
9. In addition to built-in classes PHP 5 also offers built-in interfaces. Iterator is the most important as a number of classes and interfaces are derived from this interface.
10. PHP 5 introduces a number of new "magic" methods. Magic methods begin with a double underscore and this requires changing any user-defined methods or functions that use this naming convention.
11. The major change to PHP in version 5 relating to OOP is usually summed up by saying that objects are now passed by reference.

What is the difference between session_register() and $_SESSION?

Following are differences between session_register and $_SESSION

1. session_register function returns boolean value, whereas $_SESSION returns string value.

2. session_register function does'nt work if register_global is disabled. $_SESSION works in both case whether register_global is disabled or enabled.
So using $_SESSION for session variable manipulation is more appropriate.

Which will execute faster POST or GET? Explain

POST is most secure so it have to pass some process. GET is simple way to send via URL so it is will be fast.

What is the difference between echo and print statement?

Both echo and print are language constructs.

However print() acts like a function in that it returns a value and can be used in complex expressions.

Furthermore echo without parentheses can take multiple arguments. Echo with parentheses and print can only take a single argument.

How to upload the file from one server to Remote server?

$fileToBeUploaded = "filename.txt";

$source = fopen($fileToBeUploaded,"r");
$conn = ftp_connect("ftp.myserver.com");
ftp_login($conn,"","");

ftp_fput($conn,"/path_to_folder_on_remote_server/newfile.txt",$source,FTP_ASCII);

ftp_close($conn);

Wednesday, October 21, 2009

Code for "Bookmark Us" in Javascript

Place the following script into your <head>section in the page you need to use it:

<script type="text/javascript">

function bookmark_us(url, title){

if (window.sidebar) // firefox
window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
var elem = document.createElement('a');
elem.setAttribute('href',url);
elem.setAttribute('title',title);
elem.setAttribute('rel','sidebar');
elem.click();
}
else if(document.all)// ie
window.external.AddFavorite(url, title);
}
</script>

Next, place the following code in order to show the link that opens browser's bookmark window:

<a href="javascript:bookmark_us('http://phpcoders.blogspot.com/','Php Coders')">Bookmark us!</a>

That is all! You have now a full working bookmark us script.

JavaScript Wait While Loading Page Display Image

If you have a page that takes long time to display it is a good idea to display a "wait until the page loads" image. This tutorial show you how to implement this in your webpage.

Below are the steps to implement the feature:

Step 1. Every time your page loads a "init()" function will load.

<body onLoad="init()">

Step 2. Define a div named "loading" right after <body> section.

<div id="loading" style="position:absolute; width:100%; text-align:center; top:300px;">
<img src="loading.gif" border=0></div>

The loading.gif image should be an animated gif that suggests that the page is still loading.

Step 3. Place this javascript code right after you define the div.

<script>
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
function init()
{
if(ns4){ld.visibility="hidden";}
else if (ns6||ie4) ld.display="none";
}
</script>

How to diable Right Click in JavaScript?

Neat code to restrict a user to right click and view the code or save an image. Though, it does not assure complete safety for your source (there is always a way to copy them), but it is better than nothing.

Copy & Paste this script under the HEAD in the HTML area of your webpage.

<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>

Tuesday, August 18, 2009

How to force open a window that asks to "Open" or "Save As" the file?

Below is the working example of a code that would ask the user to "Open" or "Save" the file.

Note: There should not be any output displayed above the below mentioned code i.e. the rules for "headers" in php applies here.

<?
$contentFilePath = "/docs/xyz.pdf"; // Specify the path to the file that needs to be downloaded. This could also be a file that is generated dynamically.

if ($fd = fopen ($contentFilePath, "rb")) {
$fsize = filesize($contentFilePath);
$fname = basename ($contentFilePath);

// Specify the required headers
header("Pragma: ");
header("Cache-Control: ");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$fname."\"");
header("Content-length: $fsize");

fpassthru($fd);
}
?>

Generate random alphanumeric password in Php

A simple function which returns an autogenerated random alphanumerical password with the specified length.


Code:

<?
function NewPassword($len = 8)
{
$chars=array(
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z", //upper-case
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p",
"q","r","s","t","u","v","w","x","y","z", //lower-case
"0","1","2","3","4","5","6","7","8","9" //numbers
);

srand((float) microtime() * 10000000);
$array=array_rand($chars, $len);

$password="";
foreach ($array as $key => $val)
$password.=$chars[$val];

return $password;
}
?>

Random password generation in Php

A simple random password generation function which generates various length (up to 32 characters) of password with numerals and alphabets.


Code:

<?php
function genPass($length = 8) //max length = 32 characters
{
return substr(md5(uniqid(rand(), true)), 0, $length);
}
?>

JavaScript code to strip HTML tags

This script removes any HTML tags from user entered data such as a TEXTAREA before the form is submitted. This is generally a good idea, as HTML tags can corrupt the rest of your form contents or even pose a security risk.

<script type="text/javascript">

// Strip HTML Tags (form) script- By JavaScriptKit.com (http://www.javascriptkit.com)
// For this and over 400+ free scripts, visit JavaScript Kit- http://www.javascriptkit.com/
// This notice must stay intact for use

function stripHTML(){
var re= /<\S[^><]*>/g
for (i=0; i<arguments.length; i++)
arguments[i].value=arguments[i].value.replace(re, "")
}

</script>

<form onSubmit="stripHTML(this.data1, this.data2)">

<textarea name="data1" style="width: 400px; height: 100px"></textarea><br />
<textarea name="data2" style="width: 400px; height: 100px"></textarea><br />
<input type="submit" value="submit">
</form>

Javascript Dynamic Text Area Counter

Below is the simple code to restrict the number of characters from being entered in the Text Area.


<SCRIPT LANGUAGE="JavaScript">
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) { // Trim it if too long
field.value = field.value.substring(0, maxlimit);
}
else { // otherwise, update 'characters left' counter
cntfield.value = maxlimit - field.value.length;
}
}
</script>

<form name="myForm" method="post">
<textarea name="textArea1" wrap="physical" cols="30" rows="5" onKeyDown="textCounter(document.myForm.textArea1,document.myForm.charLeft,100)" onKeyUp="textCounter(document.myForm.textArea1,document.myForm.charLeft,100)"></textarea>
<br>
<input readonly type="text" name="charLeft" size="3" maxlength="3" value="100"> characters left
<input type="Submit" name="Submit" value="Submit">
<br>
</form>

Regular Expressions Examples

Regular expression examples for decimals input

Positive Integers --- ^\d+$
Negative Integers --- ^-\d+$
Integer --- ^-{0,1}\d+$
Positive Number --- ^\d*\.{0,1}\d+$
Negative Number --- ^-\d*\.{0,1}\d+$
Positive Number or Negative Number - ^-{0,1}\d*\.{0,1}\d+$
Phone number --- ^\+?[\d\s]{3,}$
Phone with code --- ^\+?[\d\s]+\(?[\d\s]{10,}$
Year 1900-2099 --- ^(19|20)[\d]{2,2}$
Date (dd mm yyyy, d/m/yyyy, etc.) --- ^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$
IP v4 --- ^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$

Regular expression examples for Alphabetic input

Personal Name --- ^[\w\.\']{2,}([\s][\w\.\']{2,})+$
Username --- ^[\w\d\_\.]{4,}$
Password at least 6 symbols --- ^.{6,}$
Password or empty input --- ^.{6,}$|^$
email --- ^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$
domain --- ^([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$

Other regular expressions
Match no input --- ^$
Match blank input --- ^\s[\t]*$
Match New line --- [\r\n]|$

Generate a random password

Function will generate a random password with a default length of 8 or a user supplied length. Password will contain special characters, integers, and upper and lowercase characters.


Code:

<?
function newPass($maxLen=8,$pass='') {
srand((float) microtime() * 10000000);
shuffle($params=array_merge(range(0,9),range('a','z'),range('A','Z'),
array('$','_','+','*','!','%','#','@','&','-')));
for($i=0;$i<$maxLen;$i++) { $pass.=$params[rand(0,count($params)-1)]; }
unset($params);
return $pass;
}

$myNewPassword = newPass(15) # create and store a password of length 15
# Result => QEc*I#j5#cueUcZ

$myNewPassword = newPass() # create and store a password of default length 8
?>

Thursday, April 09, 2009

How to implement Complex Password Validity Tester?

How to implement Complex Password Validity Tester?

This can be implemented by using JavaScript code to force passwords to be a combination of alphabets and numbers and force range of characters.

The below code makes sure that user enters combination of alphanumeric data and check for minimum number of chars. It checks for at least one alphabetic char, special char and one numeric chars.

<html>
<head>
<script language="javascript">
function Search_Array(ArrayObj, SearchFor){
var Found = false;
for (var i = 0; i < ArrayObj.length; i++){
if (ArrayObj[i] == SearchFor){
return true;
var Found = true;
break;
}
else if ((i == (ArrayObj.length - 1)) && (!Found)){
if (ArrayObj[i] != SearchFor){
return false;
}
}
}
}

function isAlphabeticSequence (passwdString) {

var i="0",
lower = "abcdefghijklmnopqrstuvwxyz",
upper = lower.toUpperCase(),
numbers = "0123456789",
badSequenceLength = 3,
noQwertySequences = true,
qwerty = "qwertyuiopasdfghjklzxcvbnm",
start = badSequenceLength - 1,
seq = "_" + passwdString.slice(0, start),
flg1=0;

for (i = start; i < passwdString.length; i++) {
seq = seq.slice(1) + passwdString.charAt(i);
if (
lower.indexOf(seq) > -1 ||
upper.indexOf(seq) > -1 ||
numbers.indexOf(seq) > -1 ||
(noQwertySequences && qwerty.indexOf(seq) > -1)
) {
flg1++;
break;
}
}

if (flg1 > 0) {
return true;
}
return false;
}

function isAlphabeticSequenceDesc (passwdString) {

var i="0",
lower_desc = "zyxwvutsrqponmlkjihgfedcba",
upper_desc = lower_desc.toUpperCase(),
numbers_desc = "9876543210",
badSequenceLength = 3,
noQwertySequences = true,
qwerty_desc = "mnbvcxzlkjhgfdsapoiuytrewq",
start = badSequenceLength - 1,
seq = "_" + passwdString.slice(0, start),
flg1=0;

for (i = start; i < passwdString.length; i++) {
seq = seq.slice(1) + passwdString.charAt(i);
if (
lower_desc.indexOf(seq) > -1 ||
upper_desc.indexOf(seq) > -1 ||
numbers_desc.indexOf(seq) > -1 ||
(noQwertySequences && qwerty_desc.indexOf(seq) > -1)
) {
flg1++;
break;
}
}

if (flg1 > 0) {
return true;
}
return false;
}

function isAlphabeticSequenceEvenChar (passwdString) {

var i="0",
evenChars="";

//Even
for(var i=0;i<passwdString.length;i+=2) {
evenChars += passwdString.charAt(i);
}

var lower_even = "abcdefghijklmnopqrstuvwxyz",
upper = lower_even.toUpperCase(),
numbers = "0123456789",
badSequenceAltLength = 3,
noQwertySequences = true,
qwerty = "qwertyuiopasdfghjklzxcvbnm",
start = badSequenceAltLength - 1,
seq = "_" + evenChars.slice(0, start),
flg1=0;

// enforce alphanumeric/qwerty sequence ban rules
for (i = start; i < evenChars.length; i++) {
seq = seq.slice(1) + evenChars.charAt(i);
if (
lower_even.indexOf(seq) > -1 ||
upper.indexOf(seq) > -1 ||
numbers.indexOf(seq) > -1 ||
(noQwertySequences && qwerty.indexOf(seq) > -1)
) {
flg1++;
break;
}
}

if (flg1 > 0) {
return true;
}

if (isAlphabeticSequenceRevChar(evenChars)) {
return true;
}

//Check for characters such as "bab4o1", "212epj"
if (isAlphabeticSequenceRevCharDesc(evenChars)) {
return true;
}

return false;
}

function isAlphabeticSequenceEvenCharDesc (passwdString) {

var i="0",
evenChars="";

//Even
for(var i=0;i<passwdString.length;i+=2) {
evenChars += passwdString.charAt(i);
}

var lower_even_desc = "zyxwvutsrqponmlkjihgfedcba",
upper_desc = lower_even_desc.toUpperCase(),
numbers_desc = "9876543210",
badSequenceAltLength = 3,
noQwertySequences = true,
qwerty_desc = "mnbvcxzlkjhgfdsapoiuytrewq",
start = badSequenceAltLength - 1,
seq = "_" + evenChars.slice(0, start),
flg1=0;

for (i = start; i < evenChars.length; i++) {
seq = seq.slice(1) + evenChars.charAt(i);
if (
lower_even_desc.indexOf(seq) > -1 ||
upper_desc.indexOf(seq) > -1 ||
numbers_desc.indexOf(seq) > -1 ||
(noQwertySequences && qwerty_desc.indexOf(seq) > -1)
) {
flg1++;
break;
}
}

if (flg1 > 0) {
return true;
}
if (isAlphabeticSequenceRevChar(evenChars)) {
return true;
}

//Check for characters such as "bab4o1", "212epj"
if (isAlphabeticSequenceRevCharDesc(evenChars)) {
return true;
}
return false;
}

function isAlphabeticSequenceOddChar(passwdString) {

var i="0",
oddChars="";

//Odd
for(var i=1;i<passwdString.length;i+=2) {
oddChars += passwdString.charAt(i);
}

var lower_odd = "abcdefghijklmnopqrstuvwxyz",
upper = lower_odd.toUpperCase(),
numbers = "0123456789",
badSequenceAltLength = 3,
noQwertySequences = true,
qwerty = "qwertyuiopasdfghjklzxcvbnm",
start = badSequenceAltLength - 1,
seq = "_" + oddChars.slice(0, start),
flg1=0;

for (i = start; i < oddChars.length; i++) {
seq = seq.slice(1) + oddChars.charAt(i);
if (
lower_odd.indexOf(seq) > -1 ||
upper.indexOf(seq) > -1 ||
numbers.indexOf(seq) > -1 ||
(noQwertySequences && qwerty.indexOf(seq) > -1)
) {
flg1++;
break;
}
}
if (flg1 > 0) {
return true;
}

if (isAlphabeticSequenceRevChar(oddChars)) {
return true;
}

//Check for characters such as "bab4o1", "212epj"
if (isAlphabeticSequenceRevCharDesc(oddChars)) {
return true;
}

return false;
}

function isAlphabeticSequenceOddCharDesc(passwdString) {

var i="0",
oddChars="";

//Odd
for(var i=1;i<passwdString.length;i+=2) {
oddChars += passwdString.charAt(i);
}

var lower_odd_desc = "zyxwvutsrqponmlkjihgfedcba",
upper_desc = lower_odd_desc.toUpperCase(),
numbers_desc = "9876543210",
badSequenceAltLength = 3,
noQwertySequences = true,
qwerty_desc = "mnbvcxzlkjhgfdsapoiuytrewq",
start = badSequenceAltLength - 1,
seq = "_" + oddChars.slice(0, start),
flg1=0;

for (i = start; i < oddChars.length; i++) {
seq = seq.slice(1) + oddChars.charAt(i);
if (
lower_odd_desc.indexOf(seq) > -1 ||
upper_desc.indexOf(seq) > -1 ||
numbers_desc.indexOf(seq) > -1 ||
(noQwertySequences && qwerty_desc.indexOf(seq) > -1)
) {
flg1++;
break;
}
}
if (flg1 > 0) {
return true;
}

if (isAlphabeticSequenceRevChar(oddChars)) {
return true;
}

//Check for characters such as "bab4o1", "212epj"
if (isAlphabeticSequenceRevCharDesc(oddChars)) {
return true;
}
return false;
}

function isAlphabeticSequenceRevChar(passwdString) {

var i="0",
lower = "abcdefghijklmnopqrstuvwxyz",
upper = lower.toUpperCase(),
numbers = "0123456789",
badSequenceRevLength = 2,
start = badSequenceRevLength - 1,
seq = "_" + passwdString.slice(0, start),
flg1=0;

for (i = start; i < passwdString.length; i++) {

seq = seq.slice(1) + passwdString.charAt(i);
lower_seq = seq.toLowerCase();
upper_seq = seq.toUpperCase();
lower_passwdString = passwdString.toLowerCase();
upper_passwdString = passwdString.toUpperCase();

if (
(lower.indexOf(lower_seq) > -1 && (lower_passwdString.charAt(i+1)==lower_seq.substring(0,1)) ) ||
(upper.indexOf(upper_seq) > -1 && (upper_passwdString.charAt(i+1)==upper_seq.substring(0,1))) ||
(numbers.indexOf(seq) > -1 && (upper_passwdString.charAt(i+1)==upper_seq.substring(0,1)) )
) {
flg1++;
break;
}
}
if (flg1 > 0) {
return true;
}
return false;
}

function isAlphabeticSequenceRevCharDesc(passwdString) {

var i="0",
lower_desc = "zyxwvutsrqponmlkjihgfedcba",
upper_desc = lower_desc.toUpperCase(),
numbers_desc = "9876543210",
badSequenceRevLength = 2,
start = badSequenceRevLength - 1,
seq = "_" + passwdString.slice(0, start),
flg1=0;

for (i = start; i < passwdString.length; i++) {

seq = seq.slice(1) + passwdString.charAt(i);
lower_seq = seq.toLowerCase();
upper_seq = seq.toUpperCase();
lower_passwdString = passwdString.toLowerCase();
upper_passwdString = passwdString.toUpperCase();

if (
(lower_desc.indexOf(lower_seq) > -1 && (lower_passwdString.charAt(i+1)==lower_seq.substring(0,1)) ) ||
(upper_desc.indexOf(upper_seq) > -1 && (upper_passwdString.charAt(i+1)==upper_seq.substring(0,1))) ||
(numbers_desc.indexOf(seq) > -1 && (upper_passwdString.charAt(i+1)==upper_seq.substring(0,1)) )
) {
flg1++;
break;
}
}
if (flg1 > 0) {
return true;
}
return false;
}

function testPasswd(passwdString)
{
var i="0";
var cch='0';
var nr=0;
var noSequential = true;

// enforce the no sequential, identical characters rule
if (noSequential && /([\S\s])\1/.test(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric identical characters not allowed.";
return true;
}

// Check for normal sequence "abc", "123"
if (isAlphabeticSequence(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

// Check for normal sequence "cba", "321"
if (isAlphabeticSequenceDesc(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

/******** Check for alternate characters in a password string Starts here ********/
//Check for alternate characters at Even positions (start position 0 [zero]) e.g. "a3bqc", "1j2d3k"
if (isAlphabeticSequenceEvenChar(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

//Check for alternate characters at Even positions in descending order (start position 0 [zero]) e.g. "cqb3a", "3k2d1j"
if (isAlphabeticSequenceEvenCharDesc(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

//Check for alternate characters at Odd positions (start position 0 [zero]) e.g. "3aqb6c", "j1d2k3"
if (isAlphabeticSequenceOddChar(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

//Check for alternate characters at Odd positions in descending order (start position 0 [zero]) e.g. "qc3bta", "k3d2j1"
if (isAlphabeticSequenceOddCharDesc(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}
/******** Check for alternate characters in a password string Ends here ********/

//Check for characters such as "aba4o1", "121epj"
if (isAlphabeticSequenceRevChar(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

//Check for characters such as "bab4o1", "212epj"
if (isAlphabeticSequenceRevCharDesc(passwdString)) {
document.getElementById("errorMessages").innerHTML = "Alphabetic/Numeric sequence not allowed.";
return true;
}

if(passwdString.length < 8) {
document.getElementById("errorMessages").innerHTML = "A password should have at least 8 characters";
return true;
}

if(passwdString.length > 12) {
document.getElementById("errorMessages").innerHTML = "A password should have no more than 12 characters";
return true;
}

for(i=0;i<passwdString.length;i++) {
cch=passwdString.charAt(i);
if(cch >= 'a' && cch <= 'z')
nr++;
}

if(nr == passwdString.length) {
document.getElementById("errorMessages").innerHTML = "Password too simple. Please use a mix of upper and lower case letters and numerics.";
return true;
}

//It must contain at least one number character
if (!(passwdString.match(/\d/))) {
document.getElementById("errorMessages").innerHTML = "Password must include at least one number.";
return true;
}

//It must start with at least one letter
if (!(passwdString.match(/^[a-zA-Z]+/))) {
document.getElementById("errorMessages").innerHTML = "Passwords must start with at least one letter.";
return true;
}

//It must contain at least one upper case character
if (!(passwdString.match(/[A-Z]/))) {
//alert("Password must include at least one uppercase letter.");
document.getElementById("errorMessages").innerHTML = "Password must include at least one uppercase letter.";
return true;
}

//It must contain at least one lower case character
if (!(passwdString.match(/[a-z]/))) {
document.getElementById("errorMessages").innerHTML = "Password must include one or more lowercase letters.";
return true;
}

//It must contain at least one special character
if (!(passwdString.match(/\W+/))) {
//alert("Password must include at least one special character - #,@,%,!");
document.getElementById("errorMessages").innerHTML = "Password must include at least one special character - #,@,%,!";
return true;
}

// Password should contain at least 4 different character "A1#dql"
passwordString = passwdString.toUpperCase();

var arr={};
var arrAlphabets = new Array();
var temp=passwordString.split("");
for(key in temp) {
temp1=temp[key];

arr[temp1] = arr[temp1]? arr[temp1] + 1 : 1;

if (!Search_Array(arrAlphabets, temp1)) {
arrAlphabets.push(temp1);
}
}

if (arrAlphabets.length < 4 ) {
document.getElementById("errorMessages").innerHTML = "Please enter at least 4 different alphabetical characters.";
return true;
}

if ( (passwdString.match(/\d/) && passwdString.match(/\d/g).length >= 2) ){
return false;
}
else if ( (passwdString.match(/\W/) && passwdString.match(/\W/g).length >= 2) ){
return false;
}
else if ( (passwdString.match(/\d/) && passwdString.match(/\d/g).length == 1) && (passwdString.match(/\W/) && passwdString.match(/\W/g).length == 1) ){
return false;
}
else {
document.getElementById("errorMessages").innerHTML = "It must contain at least 2 non-alphabetic characters.";
return true;
}

return false;
}

function testall()
{
if(testPasswd(document.form1.txtpassword.value)) {
document.form1.txtpassword.focus();
return false;
}
document.getElementById("errorMessages").innerHTML = "";
return true;
}
</script>
</head>
<body>
<form name=form1>
<span id="errorMessages"></span><br>
<br>
<b>Enter Password:    </b><input type="text" name="txtpassword" onkeyup="return testall();">
</form>
</body>
</html>