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>

Wednesday, April 08, 2009

How websites can detect which mobile phone is viewing the website?

There is a free PHP script available on the net that detects which phone is viewing the website.

Reference URL: http://detectmobilebrowsers.mobi/

- What are the Guidelines to create a website for mobile phone?

A very good article is available on the net. Please check the below URL for details.

Reference URL: http://www.webcredible.co.uk/user-friendly-resources/web-usability/mobile-guidelines.shtml

Session ID not getting propogated in the URL properly?

When you generate URLs yourself using the SID variable, it must come first in the URL parameter list.

Example:
If SID expands to "some_session=123" then this does NOT work:

somefile.php?var1=value&some_session=123

The SID must come first in the query string:

somefile.php?some_session=123&var1=value

If the SID does not come first in the query string then session_start() does not recognise the session variable in the URL and creates a NEW session instead of loading the old one.

How to change the values in the php.ini file dynamically?

Have a look at http://de.php. net/manual/ en/ini.php# ini.list
You will see, that upload_max_filesize and post_max_size are settable by PHP_INI_PERDIR, what means that "Entry can be set in php.ini, .htaccess or httpd.conf"

Steps:
create .htaccess file and type the below code in this file

php_value upload_max_filesize 100M

and upload the file on that directory where u need it

How to capture video thumbnail with php scripting?

The tool is called imagemagick.

You have to use both ffmpeg and imagemagick as well. First get the frames from the video file using ffmpeg and then use the imagemagic command to create the thumbnails.

Refer the following sites for further details.

www. imagemagick. org/
http://ffmpeg. mplayerhq. hu/

How to resize an image to fit in the opened window?

You can use the JavaScript 'availheight' and 'height' properties (http://msdn. microsoft. com/workshop/ author/dhtml/ reference/ objects/obj_ screen.asp) to work out the size of the screen, and then use 'window.open' to open a window of that size.

Beware, not all browsers support these properties - some have there own versions, so you may need to code accordingly.

What is PHP FrameWork? And which one is good?

Frameweork is something which helps you do not reinvent the wheel again. For example, think of a authentication system. Obviously it would be having users table in database and needs the CRUD operations. How it would be if by configuration , a system gives you nearly all the functions to manipulate the user table. Or think a self build caching system, or session handling system up in just a few config settings.

Simphony is something matching ruby on rails framework and is very good. But if you do not intend to build high end applications or is light weight application your aim go for CodeIgnitor.

How can I work with XML in PHP ? What´s the best way ?

You can do it using two ways:
1. xml parser functions
2. xml dom functions

DOM functions are more complex & object oriented but handy. While parsing functions are simple to understand. Choice is yours.

How to call MySQL stored procedure in PHP with output parameter?

Check the below example.

//Say following is the store procedure you have

DELIMITER //
DROP PROCEDURE IF EXISTS yourdbname.gsp_GetCountryList //
CREATE PROCEDURE yourdbname.gsp_GetCountryList()
BEGIN
SELECT Id,strCountryName from youtable;
END//

//the above has to be run on mysql prompt


//change the php variables according to your setting


function iconnect()
{
$mysqli = new mysqli($YOURHOST, $YOURUSERNAME, $YOURPASSWORD, $YOURDATABASE);

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli;
}

$retval=iconnect();

$sql1 = "call sp1()";
$query1 = $retval->query($sql1);
while ($data1 = $query1->fetch_row()) {
echo "
\n".$data1[0].":".$data1[1];
}

How to access a file on a remote server?

There are 2 simple way to do that. First, using fopen(), second, cURL functions.

Below is a the sample code for servers that support cURL:
------------ --------- --------- --------- --------- -----
//////////// ///////// ///////// ///////// ////////
function url_exists($ strURL) {
$resURL = curl_init();
curl_setopt( $resURL, CURLOPT_URL, $strURL);
// return the result instead of echoing it
curl_setopt( $resURL, CURLOPT_RETURNTRANS FER, 1);
// time out after 5 seconds of no response
curl_setopt( $resURL, CURLOPT_TIMEOUT, 5);

$result = curl_exec ($resURL);
if ($result === false) {
curl_close($ resURL);
return false;
}

$intReturnCode = curl_getinfo( $resURL, CURLINFO_HTTP_ CODE);
curl_close ($resURL);

if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode !=
304) {
return false;
}

return true;
}
//////////// ///////// ///////// ///////// ////////

How to generate a document using php?

There are the following 2 ways to achieve this:

1. MS Office documents can be created on Windows platforms using COM called from PHP :-

http://web.informba nk.com/articles/ technology/ php-office- documents. htm

2. There's a class at http://www.phpclass es.org/browse/ package/2631. html for Word documents that doesn't require COM, but this just uses the XHTML
alternative method.

How to find GMT time for partcular locations (country) using dynamically using php script?

Using Php Script:

function zonedate($layout, $countryzone, $daylightsaving) {

if ($daylightsaving) {

$daylight_saving = date('I');
if ($daylight_saving) {
$zone=3600* ($countryzone+ 1);
}
}
else {
if ($countryzone> >0){$zone= 3600*$countryzon e;}
else {$zone=0;}
}

$date=gmdate( $layout, time() + $zone);
return $date;
}

//I'm from north of spanish state, my GMT zone is -1, put yours and you will have the time,

$zonealDate = zonedate('d- m-y H:i a ',-1,true);

echo $zonealDate;

Using Javascript:

new date();

How to download fonts dynamically, when the user is viewing the site?

Well there is a technique of uploading the font archive that you want to use to the server and use it with php and it renders it into an image the text that you use with that font.

Below is the link to check the site
http://www.alistapart.com/articles/dynatext

Warning: Unknown: Node no longer exists in Unknown on line 0 solution

I got the following error on my php pages using SimpleXMLElement and $_SESSION function.

The solution is to add a session_destroy() function at the end of any file which contains session_start() and it should work!

SEO and Dynamic Site in PHP?

If your web site is designed using PHP that displays a static/same page title from an include file for all the pages of the site, it looks like a good idea, but in a longer run you may loose on SEO ratings since all your pages would have the same page title.

Here is a better and easy way of using a single "include" file for the header while still creating unique page titles for every page. This also works for meta tags. Please check the example below.

Here you would need a header file say "header.php" that would be included at the top of every page on your site - this generates the info contained in <head>.
The page we want to create a unique title tag for will be called "product.php":

Add the below code to "header.php". An "else" statement would display a default Meta tags if you have not specified the values/variable on the website pages:

<title><?php if(isset($title)) { print $title; } else { print "Default title comes here"; } ?></title>

<meta name="keywords" content="<?php if(isset($keywords)) { print $keywords; } else { print "keyword1,keyword2,keyword3,etc"; } ?>" />

<meta name="description" content="<?php if(isset($description)) { print $description; } else { print "Default description tag goes here."; } ?>" />



Add this code to product.php to specify the info you want used in the tags:

<?php

$title = "Add title to product.php here";

$keywords = "keyword1, keyword2, keyword3, etc";

$description = "Specify description of product.php here.";

require_once("header.php");

?>

Thats it! and you are good to go! :-)

How to upload same file to 2 different Servers.

This could be done in 2 simple Steps:

1. First upload to the main server or the one where the php scripts are hosted.

2. Second, either via a cron job running after a specific time or in the upload script itself copy the files to the other server.

The below sample code is to copy the file to second server using FTP functions.

// Details of the second server.
$host = 'host';
$user = 'username';
$pass = 'password';

//Path of the uploaded file i.e. on first server.
$local_file = 'path of file/file.txt' ;

//Path of the second file.
$remote_file = 'path of file/file.txt' ;

// set up basic connection
$conn_id = ftp_connect($host);

// login with username and password
$login_result = ftp_login($conn_id, $user, $pass);

// check connection
if ((!$conn_id) || (!$login_result)) {

echo "Cannot initiate connection to host";
exit;
}
else {

// upload the file
$upload = ftp_put($conn_id, $remote_file, $local_file, FTP_BINARY);

//Close FTP connection
ftp_close($conn_id);
}