0% found this document useful (0 votes)
13 views232 pages

PHP Book To Publish - Final - Aa Devanu

The document provides an introduction to JavaScript, detailing its purpose as a client-side scripting language used for enhancing web pages. It outlines the advantages and disadvantages of JavaScript, differentiates it from Java, and explains how to write JavaScript within HTML. Additionally, it covers data types, literals, type casting, and variable creation in JavaScript.

Uploaded by

falguni.parsana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views232 pages

PHP Book To Publish - Final - Aa Devanu

The document provides an introduction to JavaScript, detailing its purpose as a client-side scripting language used for enhancing web pages. It outlines the advantages and disadvantages of JavaScript, differentiates it from Java, and explains how to write JavaScript within HTML. Additionally, it covers data types, literals, type casting, and variable creation in JavaScript.

Uploaded by

falguni.parsana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 232

1.

WRITING CLIENT SIDE SCRIPT

1.1 INTRODUCTION TO JAVASCRIPT


 JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, create cookies, and much more.
 JavaScript is the most popular scripting language on the internet, and works in all major
browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera.

WHAT IS JAVASCRIPT
 JavaScript is scripting language used for client side scripting.
 JavaScript developed by Netscape in 1995.
 JavaScript was designed to add interactivity to HTML pages.
 JavaScript is a programming language used to make web pages interactive.
 A scripting language is a lightweight programming language.
 A JavaScript consists of lines of executable computer code.
 A JavaScript is usually embedded directly into HTML pages.
 JavaScript is an interpreted language (means that scripts execute without preliminary
compilation).
 Everyone can use JavaScript without purchasing a license.
 JavaScript is case-sensitive.

ADVANTAGES OF JAVASCRIPT
 Associative Arrays.
 Loosely Typed Variables.
 Regular Expressions.
 Objects and Classes.
 Highly Evolved Date, Math, and String Libraries.
 W3c Dom Support in the Javascript.

DISADVANTAGES OF JAVASCRIPT
 Developer depends on the browser support for the JavaScript.
 There is no way to hide the JavaScript code in case of commercial application.

JAVA AND JAVASCRIPT IS NOT SAME


 NO!
 Java and JavaScript are two completely different languages in both concept and design.
 Java (developed by Sun Microsystems) is a powerful and much more complex
programming language - in the same category as C and C++.
WRITING JAVASCRIPT INTO HTML
<script language=”javascript”>

-----Javascript code------------

</script>
OR
<script type=”text/javascript”>

-----Javascript code------------

</script>

 To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script>
tag we use the "language=" attribute to define the scripting language. So, the <script
language="JavaScript"> and </script> tells where the JavaScript starts and ends:

 You can put Javascript code in both <head></head><body></body> section.

1. Head Section:
 Scripts that contain functions go in the head section of the document. Then we
can be sure that the script is loaded before the function is called.
<html>
<head>
<script language="JavaScript">
.............
.............
</script>

2. Body Section:
 Execute a script that is placed in the body section.
<html>
<head>
</head>
<body>
<script language="JavaScript">
.............
.............
</script>
</body></html>
1.2 DATA TYPES AND LITERALS

 The predefined identification of any variable is known as Data type. Or we can say
that the data type defines the characteristics of variables.
 There are six Data Types in JavaScript, three of them are Primitive or also
known as Primary data type while everything else in JavaScript is Object or
Reference Typed also known as Composite data types.

o PRIMITIVE DATA TYPES


 String
 Number
 Boolean

o REFERENCE DATA TYPES


 Object
 Array
 Function

o SPECIAL DATA TYPES


 null
 undefined

PRIMITIVE DATA TYPES


 Primitive data types are the simplest building blocks of a program. They
are types that can be assigned a single literal value such as the number 5.7,
or a string of characters such as "hello". JavaScript supports three core or
basic data types:

STRING
 String data type is use to represent text in JavaScript. A string is value
with zero or more characters which may include letters, punctuation marks
and digits. There is no separate data type for character (char) in JavaScript.
If you create a string with nothing in it, it is called an empty string. You
may use single or double quote for assigning value to string.
 These are some examples of valid string data types in JavaScript:

EXAMPLE
<script language="JavaScript">
var str1 = "Hi, How are you?";
var str2 = "He said: 'Hi'";
var str3 = 'He said:"Hi" ';
var str4 = "25";
var str5 = "";
var str6 = 'C';
</script>
NUMBER
 An integer is a base-10 whole number. In other words, it is a number with no
fractional component. JavaScript can handle integer values between 253 and -
253. Some JavaScript functions, however, cannot handle extremely large or
small numbers, so it is probably a good idea to try to keep your numbers in the
range of 231 and -231. Since that is plus or minus 2 trillion, this shouldn't be a
problem as long as you are not trying to track the national debt.
 Another commonly used type of number is a floating-point number. A
floating-point number is a number that is assumed to have a decimal point.
The decimal point is the point that floats and gives the data type its name.
 Floating-point numbers have a fractional component, even if that fractional
component is zero. They can be represented as a real number (integer -
decimal point - fractional value) such as in 3.1714, or using exponential
notation.

 Additional special value for numeric types are :


 NaN (not a number) to represent inappropriate data, as a result of
mathematical operation
 Positive Infinity represents too large positive number
 Negative Infinity represents too large negative number
 Positive and Negative 0 represent positive and negative zero(JavaScript
differentiate zero as positive or negative).

EXAMPLE
var num1 = 23; //integer value
var num2 = 42.25; //float value
var num3 = 22e5; //exponential 2200000
var num4 = 13e-5 //0.00013

BOOLEAN
 Boolean data type can only have two values, literals true and false.
Comparison of two variables wills outcome a Boolean value. Boolean are
used for condition testing.
EXAMPLE
<script language="JavaScript">
var num1=54;
var result = (num1 === 2000); //will return false
var result1 = (num1 === 54); //will return true
document.write(result);
</script>
REFERENCE DATA TYPES

OBJECTS
 An object is a collection of named values, called the properties of that object.
Functions associated with an object are referred to as the methods of that
object.
 Properties and methods of objects are referred to with a dot.notation that starts
with the name of the object and ends with the name of the property. For
instance image.src.
 Normally in objects there are only two nodes, the object and the property, but
as we will discover, sometimes the properties can have properties of their
own, creating an object tree which you have to specify the path through in the
same way you would with a directory tree (except you are using periods
instead of slashes).
 For instance, document.form1.namefield.
 Objects in JavaScript can be treated as associative arrays. This means that
image.src and image['src'] are equivalent. This flexibility has its uses, since
this means that you can pass property names as the values of variables.
 For instance, this code snippet: img[iProp] = newImage[iProp];
 JavaScript has many predefined objects, such as a Date object and a Math
object. These are used much as function libraries are used in a language like
C. They contain a collection of useful methods that are predefined and ready
for use in any JavaScript code you may write.

ARRAY
 Array is collection containing zero or more items. Array items can be access
by using indexing on variable. In JavaScript specifications typeof Array is
object.

EXAMPLE
<script language="JavaScript">
var dataTypes=new Array();
dataTypes[0]="String";
dataTypes[1]="Number";
dataTypes[2]="Boolean";
//condensed array:
dataTypes=new Array("String","Number","Boolean");
//literal array:
dataTypes=["string","number","boolean"];
</script>
FUNCTION
 A function is a piece of code, predefined or written by the person creating the
JavaScript that is executed based on a call to it by name.
 A function is a data type in JavaScript. This is different from many other
programming languages. This means that they can be treated as containing
values that can be changed.
EXAMPLE
<script language="JavaScript">
var myFunc = function(){
alert("function is triggered");
};
myFunc();
</script>

SPECIAL DATA TYPES


 NULL
 The value for null data type can only be null. keyword null is use to assign
null to any variable. It can be use to emptied content of any variable without
deleting the variable. A variable with null data type contains no valid other
data types.
EXAMPLE
var type = null;
var obj = null;

UNDEFINED
 The undefined value is default for a variable which is declared but never
assigned a value.
EXAMPLE
var myVar;
if((typeof var) === "undefined")
{
alert("variable is undefined");
}

1.3 LITERALS
Javascripts can’t support data types. But it supports Literals.

Literals are used to represent values of variables of particular data type in JavaScript.

These are fixed values not variables that you literally provide in your script.

Integer Literals :

 Integer Literals can be expressed as Whole Numbers without any decimal


points.
 It can be positive or negative number.
 Example :

 var a = 112;
 var b = - 44;

Floating Point Literals:

 Floating Point Literals can be expressed as numbers with decimal points.


 It can be positive or negative number.
 Example :

 var a = 1.23;
 var b = -4.9;

Boolean Literals:

 Boolean Literals can be expressed as only with two values i.e. TRUE or FALSE.
 You can just assign true or false values, it will automatically take 0 as true value and 1 as
false value.
 Example :

 var a = true;
 var b = false;

String Literals:

 String Literals can be expressed as a sequence of characters. It always enclose with either
single quote(‘) or double quotes(“).
 Example :

 var str1 = “Hello”


 var str2 = ‘World’

Array Literals:
 Array Literals can be expressed as a list of values that are called elements of Array.
 The values may be numbers, strings or any type of Literal.
 Example :

 Var arr = new Array(3)


 arr[0] = “one”
 arr[1] = “two”
 arr[2] = “three”

Object Literals:

 Object Literals can be expressed as a list of pairs of property names and associated values
of an Object enclosed in { }.
 NOTE: It is just a User Defined Object which is shown later on.

NULL Literals:

 Null Literal consists of single value, which identifies a NULL i.e. empty.
 It is used to set initial value of variable that is different from other valid values.
 Example:

 var temp = null;


 Document. write(“Value of temp is :”+temp);

1.4 TYPE CASTING

 JavaScript is a loosely typed language meaning a variable can hold any data type at any
time. The data types are categorized as primitive and Composite, where a Primitive data
type holds single piece of data and a Composite data type holds a collection. The
Primitive data types are generally known to be Numbers, Strings and Booleans, while
Composite types are known to be Objects, Literals, Arrays and Functions.
 By default JavaScript attempts to perform all required type conversions at the appropriate
times, but sometimes it is necessary to force cast a variable. A good example of this is
when returning a value from a function, where the return data type is expected in a
certain form.

Conversion Rules
JavaScript will attempt to carry out the specified conversions in the following situations:
 Boolean is converted to a Number (1/0) before comparison.
 In a Number comparison, if an entry is NaN it will be converted to false.
 Also when comparing a Number, if an Object is entered it will attempt to cast it to an
Integer.
 If two Objects are compared it is the memory address that is checked for comparison.
 The Literals ‘null’ and ‘Undefined’ are judged to be the same entity. They will not cast to
0, “” or false.
 If a String and a Number are compared, the String will be cast to an Integer.
 If an Object and a String are compared, the Object will be cast to a String.

STRINGS
 All Primitive data types in JavaScript are included with a ‘toString()’ method
which can be called manually to convert the data type to a string. When
dealing with floats, JavaScript will not maintain decimal places that are not
required. This method also has an optional radix parameter which can be used
to change the base level of the returned number.

1.5 CREATING VARIABLE

Javascript Variables

 Variables are "containers" for storing information.


 As with algebra, JavaScript variables are used to hold values or expressions.
 A variable can have a short name, like x, or a more describing name like length.
 A JavaScript variable can also hold a text value like in cityname="rajkot".
 A variable's value can change during the execution of a script.
 You can refer to a variable by its name to display or change its value.
 Unlike a lot of things in HTML, JavaScript are case sensitive. So a variable named
“sum” is not the same as “Sum" or “SUM".

How to declare Variable in Javascript?


SYNTAX:
var name=value;

var
This indicates you are about to declare a variable.

name

This is the name you give the variable.

value

This is the initial value you want the variable to have. It can be a number,
words, true, false, or null.

EXAMPLE:
var cars;
var cost;
Assign value to variable
VAR CARS=3;
VAR COST=9.95;
VAR MOVIE="THE LOST WORLD";
VAR STORY=TRUE;
VAR MYMONEY=NULL;

Incorporating variables in a Javascript


Incorporating Variables in Javascript means you can use javascript variable into your html.

EXAMPLE 1

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var name=prompt("Enter Your Name:","Name");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
document.write('<IMG SRC="Chrysanthemum.jpg">');
document.write("<H1>Greetings, " + name + ". Welcome to JavaScript</H1>");
</SCRIPT>
</BODY>
</HTML>

EXAMPLE 2
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var name=prompt("Enter Your Name:","Name");
alert("Greetings " + name + ".");
name=prompt("Enter Your Friend's Name:","Friend's Name");
</SCRIPT>
</HEAD>
1.6<BODY>
JAVASCRIPT ARRAY
<SCRIPT LANGUAGE="JavaScript">
document.write('<IMG SRC="Chrysanthemum.jpg">');
document.write("<H1>Greetings, " + name + ". Welcome JavaScript</H1>");
</SCRIPT>
</BODY>
</HTML>
 Using arrays, you can store multiple values under a single name. Instead of using a
separate variable for each item, you can use one array to hold all of them.
 The index number is the location of the data element in the array.
 Each stored value so indexed is referred to as an array element.
 The order of the elements is fixed
 The Array object is used to store a set of values in a single variable name.
 We define an Array object with the new keyword.

TYPES OF ARRAY
1. One Dimensional Array
2. Two Dimensional Array
3. Multidimensional Array

1. ONE DIMENSIONAL ARRAY


 Basic arrays represent one or more values separated by commas. The values can be a
mixture of strings, numbers and variables.
 Each array item gets an index number associated with it which is its key.
 There are multiple ways to parse and access the elements of an array.
 You cannot access array out of index.

SYNTAX
var array-name = new Array( number-of-values)

EXAMPLE
var product_name = new Array(“Nokia”,”LG”,” Samsung”)

OR
Size of array is defined based on array element.

SYNTAX
var array-name = new Array( number-of-elements )
Or
var array-name = new Array( )

EXAMPLE
var product_name = new Array(3)
Product_name[0]=”PHP”;
product_name[1]=”C++”;
product_name[2]=”VB”;
product_name[3]=”JAVASCRIPT”;
Where Array() is constructor and "new" keyword to instantiate the array in memory.

ASSOCIATIVE ARRAY
 Associative arrays give you a way to label your array item keys instead of them being
numbered in the way that array elements are usually numerically indexed by default.
 The key is directly associated to its value in a meaningful way.

EXAMPLE
var my_cars= new Array()
my_cars["cool"]="pradip";
my_cars["family"]="vsc-project";
my_cars["big"]="rajkot";
for (i in my_cars)
{
document.write(i+"<br>");
}

2. TWO DIMENSIONAL ARRAY


 Two-dimensional arrays, the most common multidimensional arrays, are used to store
information that we normally represent in table form.
 This means that all of the data in a two-dimensional array is of the same type. Examples
of applications involving two-dimensional arrays include:
o a seating plan for a room (organized by rows and columns),
o a monthly budget (organized by category and month), and
o a grade book where rows might correspond to individual students and columns to
student scores.

SYNTAX

EXAMPLE
<html><head>
<script language="javascript">
Subject= new Array (3);
for (i = 0; i < Subject.length; ++ i)
Subject[i] = new Array (3);

Subject[0] [0] = "HTML";


Subject[0] [1] = "CSS";
3. MULTI-DIMENSIONAL ARRAY
 A multidimensional array is an array that is holding multiple arrays that can be of various
types.
SYNTAX

EXAMPLE
<script language="javascript">
var myarr=new Array(["HTML","CSS","JAVASCRIPT"],["PHP","ASP.NET","VB.NET","C#.NET"],
"VB","FOXPRO","MSACCESS"]);
document.write(myarr[0]);
document.write("<br>"+myarr[1]);
document.write("<br>"+myarr[2]);
</script>

1.7 OPERATORS AND EXPRESSIONS IN JAVASCRIPT


OPERATORS

 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 String Operators
 Conditional Operator

ARITHMETIC OPERATORS
 Assignment operators are used to assign values to JavaScript variables.

 Given that x=10 and y=5, the table below explains the assignment operators:

Operator Description Example Result

+ Addition x=y+2 x=7

- Subtraction x=y-2 x=3

* Multiplication x=y*2 x=10

/ Division x=y/2 x=2.5

% Modulus (division remainder) x=y%2 x=1

++ Increment x=++y x=6

-- Decrement x=--y x=4

COMPARISON OPERATORS

 Comparison operators are used in logical statements to determine equality or


difference between variables or values.
 Given that x=5, the table below explains the comparison operators:

Operator Description Example

== is equal to x==8 is false


=== is exactly equal to (value and type) x===5 is true
x==="5" is false

!= is not equal x!=8 is true

> is greater than x>8 is false

< is less than x<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true

LOGICAL / BOOLEAN OPERATORS

 Logical operators are used to determine the logic between variables or values.
 Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true

BITWISE OPERATORS

 Bitwise operators perform an operation on the bitwise (0,1) representation of their


arguments, rather than as decimal, hexadecimal, or octal numbers.
 For example, the decimal number eight has a binary representation of 1000.
 Bitwise operators do their operations on such binary representation (for example
1000) but they return standard JavaScript numerical values.
 the table below explains the bitwise operators:

Operator Description Example

Bitwise AND a&b Returns a one in each bit position if bits of


both left and right operands are ones.
Bitwise OR a|b Returns a one in each bit if bits of either left
or right operand is one.

Bitwise XOR a^b Returns a one in a bit position if bits of one


but not both left and right operand are one.

Bitwise NOT ~a Flips the bits of its operand.

Left shift Shifts a in binary representation b bits to the


a << b
left, shifting in zeros from the right.

Sign-propagating Shifts a in binary representation b bits to the


a >> b
right shift right, discarding bits shifted off

Zero-fill right Shifts a in binary representation b bits to the


shift a >>> b right, discarding bits shifted off, and shifting
in zeros from the left.

ASSIGNMENT OPERATORS

 Assignment operators are used to assign values to JavaScript variables.


 Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result

= x=y x=5

+= x+=y x=x+y x=15

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0

STRING OPERATORS
 The + operator can also be used to concatenate (add) strings.

EXAMPLE

txt1 = "What a very";


txt2 = "nice day";
txt3 = txt1 + txt2;
CONDITIONAL OPERATOR
 The conditional operator is used as a shortcut for standard if statement. It takes three
operands.
SYNTAX
Condition ? expr1 : expr2
PARAMETER

condition : An expression that evaluates to true or false.


expr1, expr2 : Expressions with values of any types.

If condition is true, the operator returns the value of expr1; otherwise, it returns the
value of expr2.
EXAMPLE

status = (marks >= 30) ? "Pass" : "Fail"

EXPRESSIONS

o An expression is any valid unit of code that resolves to a value.

o TWO TYPES OF EXPRESSIONS:


 ASSIGN A VALUE TO A VARIABLE
 SIMPLY HAVE A VALUE.

o The expression x = 7 is an example of the first type. This expression uses the =
operator to assign the value seven to the variable x. The expression itself evaluates to
seven.
o The code 3 + 4 is an example of the second expression type. This expression uses the
+ operator to add three and four together without assigning the result, seven, to a
variable.

o JAVASCRIPT HAS THE FOLLOWING EXPRESSION CATEGORIES:


 Arithmetic: evaluates to a number, for example 3.14159.
 String: evaluates to a character string, for example, "Fred" or "234".
 Logical: evaluates to true or false.
 Object: evaluates to an objects
SPECIAL OPERATORS

The following are 3 very important operators


 The Conditional Operator
 Typeof Operator
 Void Operator

THE CONDITIONAL OPERATOR


o The conditional operator is the only operator that takes three operands. It is basically
the short hand version of an if-else statement.
o The first operand, located before the question mark, is a conditional expression that is
tested for a true or false value. On either side of the colon are the second and third
operands.
o The second operand is an expression that will evaluate if the condition is true, and the
third is an expression will evaluate if the condition is false.
o The assignment operator is frequently used with the conditional operator to assign
one of the two expressions to a variable.
SYNTAX
?:

( a ? x : y ) if a is true, then a equals x. otherwise a equals y

EXAMPLE
var mood = (smile==true) ? happy : sad

TYPEOF OPERATOR
o The typeof operator is used to get the data type (returns a string) of its operand.The
operand can be either a literal or a data structure such as a variable, a function, or an
object. The operator returns the data type.
SYNTAX
typeof operand or typeof (operand)

o There are six possible values that typeof returns: object, boolean, function, number, string,
and undefined. The following table summarizes possible values returned by the typeof
operator.
Type of the operand Result

Object "object"

Boolean "boolean"

Function "function"

Number "number"

String "string"

Undefined "undefined"

EXAMPLE
<script language="JavaScript">
var a;
typeof a; //"undefined"
typeof b; //"undefined"
alert(a); //undefined
alert(b); //ReferenceError
var index = 8;
var result = (typeof index === 'number');
alert(result); // Output: true
var description = "w3resource";
var result = (typeof description === 'string');
alert(result); // Output: true
</script>

VOID
o The void operator is used to evaluate a JavaScript expression without returning a
value.
SYNTAX
void expression

EXAMPLE
<script language="javascript">
function testfunc()
{
alert ("testfunc");
}
</script>
</head>
<body>
<a href="javascript:void(alert('Thank you.'))">Click here to see a message</a>
<a href="javascript:void(testfunc())"> Click here to call testfunc()</a>
</body>
1.8 CONSTRUCTOR

 In the world of OOP, the previous ways of defining an object is too limiting in many
situations. We need a way to create an object "type" that can be used multiple times
without having to redefine the object every time to meet each particular instance's
needs. The standard way to achieve this is to use the Object Constructor function.
 A constructor is any function which is used as a constructor. The language doesn’t make a
distinction. A function can be written to be used as a constructor or to be called as a normal
function, or to be used either way.
 A constructor is used with the new keyword:

var Vehicle = function Vehicle() {


// ...
}

var vehicle = new Vehicle();

WHAT HAPPENS WHEN A CONSTRUCTOR IS CALLED?


o When new Vehicle() is called, JavaScript does four things:
 1. It creates a new object.
 2. It sets the constructor property of the object to Vehicle.
 3. It sets up the object to delegate to Vehicle.prototype.
 4. It calls Vehicle () in the context of the new object.
o The result of new Vehicle() is this new object.

OBJECT CONSTRUCTOR AND PROTOTYPING


o An object constructor is merely a regular JavaScript function, so it's just as robust (ie:
define parameters, call other functions etc). The difference between the two is that a
constructor function is called via the new operator (which you'll see below). By
basing our object definition on the function syntax, we get its robustness as well.
o The origins of constructor
o When you declare a function:
function Rabbit() { /* ..code.. */ }

o The interpreter creates the new function object from your declaration. Together with
the function, its prototype property is created and populated.
o This default value the prototype is an object with property constructor, which is set to
the function itself. In our case, to Rabbit:
Rabbit.prototype = { constructor: Rabbit }

So, when new Rabbit is called, the Rabbit.prototype becomes __proto__ and
the constructor becomes accessible from the object:
rabbit.__proto__ == { constructor: Rabbit )

Let’s make a direct check:

EXAMPLE
function Rabbit() { }
var rabbit = new Rabbit()
alert( rabbit.hasOwnProperty('constructor') ) // false
alert( Rabbit.prototype.hasOwnProperty('constructor') ) // true

1.9 CONDITION CHECKING

Conditional statements
 A conditional statement uses conditional logic to determine what programming
statements to execute.
 By using some conditional logic (a process of checking conditions), we determine if a
certain condition is true or false.
 If the condition is true, we execute some part of the program. Otherwise, if the
condition is false, we use some other part of the program.
 In JavaScript we have the following conditional statements:
o if statement
o if...else statement
o if...else if....else statement
o switch statement

IF STATEMENT
 You should use the if statement if you want to execute some code only if a specified
condition is true.
SYNTAX
if (condition)
{
code to be executed if condition is true
}

EXAMPLE
<script language="JavaScript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

IF...ELSE STATEMENT
 If you want to execute some code if a condition is true and another code if the
condition is not true.
SYNTAX
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

EXAMPLE
<script language="JavaScript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
IF...ELSE IF....ELSE STATEMENT
 You should use the if....else if...else statement if you want to select one of many
sets of lines to execute.
SYNTAX
if (condition1)
{ code to be executed if condition1 is true }
else if (condition2)
{ code to be executed if condition2 is true }
else
{ code to be executed if condition1 and
condition2 are not true
}

EXAMPLE
<script language="JavaScript">
var d = new Date();
var time = d.getHours();
if (time<10)
{document.write("<b>Good morning</b>");}
else if (time>10 && time<16)
{document.write("<b>Good day</b>");}
else
{document.write("<b>Hello World!</b>");}
</script>

SWITCH STATEMENT
 Conditional statements in JavaScript are used to perform different actions based
on different conditions.
 This is how it works:
o First we have a single expression n (most often a variable), that is evaluated
once.
o The value of the expression is then compared with the values for each case in
the structure.
o If there is a match, the block of code associated with that case is executed.
o Use break to prevent the code from running into the next case automatically.
SYNTAX
switch(n)
{
case 1:
execute code block 1
break;
case 2:
EXAMPLE
execute code block 2
<script language="JavaScript">
break;
//You will receive a different greeting based
default:
//on code today
what it is. Noteifthat
be executed n is Sunday=0,
//Monday=1, Tuesday=2,
different from case 1 and 2etc.
var} d=new Date();
var theDay=d.getDay();
switch (theDay)
{ ENDLESS LOOP
case 5:
document.write("Finally Friday");
break;
case 6: FUNCTIONS IN JAVASCRIPT
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
USER DEFINE FUNCTION
default:
document.write("I'm looking forward to this weekend!");
}
</script>

1.10 ENDLESS LOOPS


 If you want the same block of code to run a number of times. You can use looping
statements in your code to do this.
o while
o do...while
o for

WHILE
 The while statement will execute a block of code while a condition is true.
SYNTAX
while (condition)
{
code to be executed
}
EXAMPLE
<html>
<head>
<script language="javascript">
i=0;
DO...WHILE while(i<=5)
 The do...while { statement will execute a block of code once, and then it will repeat
the loop whiledocument.write(i+"<br>");
a condition is true.
SYNTAX i++;
}
do
</script>
{
</head><body></body></html>
code to be executed
}
while (condition)

EXAMPLE

<html><body>
<script type="text/javascript">
i=0
do
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
i++
}
while (i<=5)
</script>
</body></html>

FOR
 The for statement will execute a block of code a specified number of times
SYNTAX
for (initialization; condition; increment)

{ code to be executed }

EXAMPLE

<html>
<body>
<script type="text/javascript">
for (i=0; i<=5; i++)
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
}
</script>
</body>
1.11 WHAT IS USER DEFINE FUNCTION?
 A function is a reusable code-block that will be executed by an event, or when the
function is called.
 Function provides the ability to combine no. of statements in single unit.
 JavaScript provides Functions through which you can perform certain task.
 JavaScript allows users to create our own Functions, are called “User Defined
Functions”.
 User Defined Function first need to be declared after that function can be invoked by
calling it using its name when it was declared.
 The data needed to execute a function is passed as a Parameter.

HOW TO DECLARE A FUNCTION?

function function-name([parameter list])


{
block of statements [return statement]
}  Functions are declared and created using “function” keyword.
 “function-name” is the appropriate name of the function.

 “parameter-list” are optional and passed to the function appears in parentheses and
commas separate member of list.
 “return” statement can be used to return any valid expression that Evaluates a single
value.
EXAMPLE
<html> <head>
<script language=”javacript”>
function displayMsg( )
{
alert(“Welcom to Digital City…”);
}
</script> </head>
<body>
<input type=”button” value=”Click Here” onClick=”displayMsg()”>
</body> </html>

TYPES OF USER DEFINE FUNCTION

o No Argument & No Return Value


o With Argument & No Return Value
o No Argument & With Return Value
o With Argument & With Return Value

NO ARGUMENT & NO RETURN VALUE

 Function accepts argument but it does not return a value back to the calling Program.

EXAMPLE
<html> <head>
<script language="javascript">

function simple()
{

alert("Function is Call");
}

</script>
</head>
<body>
<input type="button" value="Click Me!" onclick="simple()">
</body>
</html>

WITH ARGUMENT & NO RETURN VALUE


 Function accepts argument but it does not return a value back to the calling Program .
SYNTAX
function function_name(parmeter_1,parameter_2)
{
Javascript Code…
}
</script>
function_name(value_1,value_2)

EXAMPLE
function simple(a,b)
{
var c=a+b;
alert(c);
}

</script>
<input type="button" value="Click Me!" onclick="simple(10,20)">
NO ARGUMENT & WITH RETURN VALUE
 Function does not accepts argument but it return a value back to the calling Program .
SYNTAX
function fun_name()
{
--- code -----
return variale;
}
fun_name();

EXAMPLE
function simple()
{
var a=10;
var b=20;
var c;
c=a+b;
return c;
}
document.write(simple());

WITH ARGUMENT & WITH RETURN VALUE


 Function accepts argument and it return a value back to the calling Program.
SYNTAX
function fun_name(var1, var2)
{
return c;
}

function_name()

EXAMPLE
function simple(a,b)
{
var c;
c=a+b;
return c;
}
document.write(simple(20,20));
1.12 BUILT-IN FUNCTIONS

1. eval()

The eval() function evaluates a string without reference to a particular objects.

Syntax:
eval(string-expression)

Example:

<script language=”javascript”>

var no1 = prompt(“Enter First Value”);

var no2 = prompt(“Enter Second Value”);

s = eval(no1) + eval(no2);

document.write(“Sum : ”+s);

</script

2. parseInt()

The parseInt() function parses a string and returns an integer.

Syntax:

parseInt(string)

Example:

<script language=”javascript">
document.write(parseInt("15") + "<br />");
document.write(parseInt("15.34") + "<br />");
document.write(parseInt("25 35 45") + "<br />");
document.write(parseInt(" 100 ") + "<br />");
document.write(parseInt("30 years") + "<br />");
document.write(parseInt("Hello") + "<br />");
document.write(parseInt("15",10)+ "<br />");
document.write(parseInt("015")+ "<br />");
document.write(parseInt("15",8)+ "<br />");
document.write(parseInt("0x10")+ "<br />");
document.write(parseInt("10",16)+ "<br />");</script>

Output:

15
15
25
100
30
NaN

15
8
8
16
16

3. parseFloat():

The parseFloat() function parses a string and returns a floating point number.

This function determines if the first character in the specified string is a number.
If it is, it parses the string until it reaches the end of the number, and returns the
number as a number, not as a string.

Syntax:

parseFloat(string);

Example:

<script type="text/javascript">
document.write(parseFloat("15") + "<br />");
document.write(parseFloat("15.46") + "<br />");
document.write(parseFloat("35 45 55") + "<br />");
document.write(parseFloat(" 100 ") + "<br />");
document.write(parseFloat("30 years") + "<br />");
document.write(parseFloat("Hello") + "<br />");
</script>

Output:

15
15.46

35

100

30

NaN

1.13 DIALOG BOXES

 JavaScript supports three important types of dialog boxes.


 These dialog boxes can be used to raise and alert, or to get confirmation on any input
or to have a kind of input from the users.
o Alert box
o Confirm box
o Prompt box

ALERT BOX
 An alert box is often used if you want to make sure information comes through to the
user.
 When an alert box pops up, the user will have to click "OK" to proceed.
 The alert() method is used for this type of use include
o Incorrect information in a form.
o An invalid result from a calculation.
o A warning that a service is not available on a given date.

SYNTAX
alert("sometext");

EXAMPLE
<html>
<head>
<script language="javascript">
function msgbox()
{
alert("This is an Alert Box");
}
</script>
</head><body>
<input type="button" value="alert box" onClick="msgbox()">
</body></html>
Output
CONFIRM BOX
 A confirm box is often used if you want the user to verify or accept something.
 When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
 Confirm displays a dialog box with two buttons: OK and Cancel.
 If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.

SYNTAX
confirm("sometext");

EXAMPLE
<html> <head><script language="javascript">
function msgbox()
{
var ans=confirm("Are You Agree !");
if(ans=="true")
{ alert("You have Press Ok Button"); }
else
{ alert("You have Press Cancle Button"); }
}
</script></head><body> <input type="button" value="confirm box"
onClick="msgbox()"> </body></html>
Output

PROMPT BOX

 A prompt box is often used if you want the user to input a value before entering a
page.
 When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
 If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
SYNTAX
var variable-name=Prompt(“sometext”,”defaultvalue");

EXAMPLE

<html><body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
1.14 JAVASCRIPT {
OBJECT
var x;
if (confirm("Press
What is Object? a button!") == true) {
x = "You pressed OK!";
} else
 “Object” is{ just a special kind of data. Each Object have its state and behavior.
x =the
 State of "You pressed
Object Cancel!";
refers as Property.
}
 Behavior of the Object refers as Methods.
document.getElementById("demo").innerHTML = x;
}
Properties:
</script></body></html>
Output are used to define the characteristics of an Object.
 Properties
 Properties are used to access the data values present in the object.
 To access the property of an Object:-
o ObjectName.propertyName

Methods:

 Methods are the actions that can be performed on Objects.


 Object’s behaviour, we can change by using accessing their methods.
 To access the method of an Object:-
You
o pressed OK!
ObjectName.methodName

 Javascript is object-oriented scripting language. So Javascript allows you to use with


objects.
 Javascript provides two types of Objects

Built-In Objects :
 Javascript provides two types of Built-In Objects.
 Native Objects
o String Object
o Math Object
o Array Object
o Date Object

 Browser Objects
o Window Object
o History Object
o Location Object
o Screen Object
o Navigator Object
o Document Object

String Object:

This object is used to manipulate the String.

Property:

Length Returns the no. of characters in a String.

Methods:

o bold:
o italics:
o strike:
o sup:
o sub:
o fontcolor:
o fontsize:
o link:
o blink:
o charAt:
o concat:
o indexOf:
o lastIndexOf:
o match:
o replace:
o search:
o slice:
o substr:
o substring:
o toLowercase:
o toUppercase:

 bold:
o This method is used to display a string in a bold font.
Syntax:
Stringobject.bold()
 Italics:
o This method is used to display a string in italics font.

Syntax:
Stringobject.italics()
 Big:
o This method is used to display a string in big font.
Syntax:
Stringobject.big()
 Small:
o This method is used to display a string in small font.
Syntax:
Stringobject.small()
 Sub:
o This method is used to give subscript effect to the string.
Syntax:
Stringobject.sub()
 Sup:
o This method is used to give superscript effect to the string
Syntax:
Stringobject.small()
 Fontsize:
o This method is used to specify the size of font.
Syntax:
Stringobject.fontsize(size)
 Fontcolor:
o This method is used to specify the color of font.
Syntax:
Stringobject.fontcolor(color)

You can specify the color in 3 ways:


By specifying the color code.
By specifying the color name.
By using the rgb() function as an argument.
 Blink
o This method is used to display a blinking string.
o Can’t support by the internet explorer.
Syntax:
Stringobject.blink()
 Link:
o This method is used to display a string as a hyperlink.
Syntax:
Stringobject.link()
 Strike:
o This method is used to give strikethrough effects to the string.

Syntax:
Stringobject.strike()
Example:
<script language=”Javascript”>
var myString = "Good Morning"
var myString2 = " Happy World”
var str=”st”;
var str1=”2”;
document.write("<b>My String is</b>: "+myString);
document.write("<b>Bold</b> : "+myString.bold());
document.write("<b>Italics</b> : "+myString.italics());
document.write("<b>Strike</b>: "+myString.strike());
document.write("<b>Superscript</b> : 1"+str.sup());
document.write("<b>Subscript</b>H : "+str1.sub()+”O”);
document.write("<b>FontColor</b>:"+myString.fontcolor("red”) );
document.write("<b>FontColor</b>"+myString.fontcolor("rgb (0,255,0)") );
document.write("<b>FontColor</b>:String.fontcolor("0000FF");
document.write("<b>FontSize</b> : "+myString.fontsize(15));
document.write("<b>Link</b>"+myString.link("javascript") )

 CharAt:
o The charAt () method is used to find the character at specified position.
o This method is case sensitive.
Syntax:
Stringobject.charAt(index)
Example:
Var str=”My string”
document. write(charAt(3));
Output:
S

 Concat:

o This method is used to concat (merge) two or more strings.


Syntax:
Stringobject.concat (stringX,stringX,……X)

Example:
Var st1=”This is“
Var st2=”Computer”
Docement.write(st1.concat(st2))
Output:
This is computer

 indexOf:
o this method returns the position of the first occurrence of a specified string value
in a string object.
o It is case sensitive.
o Returns -1 if no match found.
Syntax:
Stringobject.indexOf(stringvalue,startIndex)
Here the string value is required and start index is optional.

Example:
Str=”Have a nice Day”;
document.write(str.indexOf(“Have”))
document.write(str.indexOf(“Nice”))

output:
0
-1

 lastIndexOf:
o This method returns position of the last occurrence of a specified string value.
o It is case sensitive.
o It returns -1 if no match found.
Syntax:
Stringobject.lastIndexOf(stringValue,startIndex)
Example:
Var str=”Hello World”
document.write(str.lastIndexOf(“o”))
Output:
7
 match
o It searches for specified string value in a string.
o It is similar to indexOf() and lastIndexOf(), but returns specified string, instead of
position of the string.
o Case sensitive.
o Returns null if no match found.
Syntax:
stringObject.match(search value)
Example:
Str=”Have a nice Day”;
document.write(str.indexOf(“Have”))
document.write(str.indexOf(“Nice”))
Output:
Have
Null

 Replace:
o The replace() method is used to replace some characters with some other
characters in a string.
o The replace() method is case sensitive.

Syntax:
stringObject.replace (findstring, newstring)
Example:
Var str=”Play Cricket”;
Document.write (str.repalce (“Cricket”,” Chess”)
Output:
Play Chess

 Search:
o The search() method is used to search a string for specified value.
o The search() method returns the position of the specified value in the. If no match
was found it returns -1.
o This method is case sensitive.
Syntax:
StringObject.search(searchvalue)
Example:
Var str=”Have a nice day”
Document.write (str.search (“day”))
Output:
12
 Slice:
o The slice() method extracts a part of a string and returns the extracted part in a
new string.
o You can use negative numbers to select from the end of the string.
o If the end is not specified, slice () selects all characters from the specified start
position and to the end of the string.
Syntax:
stringObject.slice(start,end)

Example:
Var str=”Hello, How are you?”
Document.write(str.slice(6));
Document.write(str.slice(6,11));
Output:
How are you?
How ar

 Substr:

o The substr() method extracts a specified number of characters in a string.


o To extracts from the end of the string, use a negative start number. The start index
starts at 0.
o If the length parameter is omitted, this method extracts to the end of the string.
Syntax:
stringObject.substr(start,length)
Example:
Var str=”Good Morning”;
Document.write(str.substr(3));
Document.write(str.substr(3,7));
Output:
D Morning
D Morni

 Substring:
o The substring () method extracts the characters in a string between two specified
indices.
o To extract the character from the end of the string, use negative start number. The
start index starts at 0.
o If the stop parameter is omitted, this method extracts to the end of the string.
Syntax:
stringObject.substring(start,stop)
Example:
Var str=”Hello world”;
Document.write(str.substr(3))
Document.write(str.substr(3,7))
Output:
Lo world
Lo w

 toLowerCase:
o The toLowerCase() method is used to display a string in lowercase letters.
Syntax:
stringObject.toLowerCase()
Example:
Var str=”Hello World!”
Output:
hello world!
 toUpperCase:
o The toUpperCase() method is used to display a string in up-percase letters.

Syntax:
stringObject.toUpperCase()
Example:
Var str=”Hello World!”
Output:
HELLO WORLD!
STRING OBJECT PROPERTY:
 length:
o This property is used to count the length of the specified string.
Syntax:
stringObject.length
Example:
Var str=”Hello World”;
Output:
11

Math Object:

Math Object provides standard library of mathematical constants and functions.

The “Constants” are defined as properties of Math Obect.

The “Functions” are defined as methods of Math Object.

Methods:

 abs:
 It returns absolute value of a number.
Syntax:
Math.abs(number)

Example:
document.write(Math.abs(-7.25));

document.write(Math.abs(7.25));

 ceil:
 It returns value of number rounded UPWARDS to the nearest integer.
Syntax:
Math.ceil(number)

Example:
Document.write(Math.ceil(0.60))

Document.write(Math.ceil(0.40))

Document.write(Math.ceil(- 5.1))

Document.write(Math.ceil(5.1))

 floor:
 It returns the value of number rounded DOWNWARDS to the nearest integer.
Syntax:
Math.floor(number)

Example:
document.write(Math.floor (0.60))

document.write(Math. floor (0.40))

document.write(Math. floor (- 5.1))

document.write(Math. floor (5.1))

 cos:
 It returns the value of cosine of number.
 It returns numeric value between -1 to 1.
Syntax:
Math.cos (number)

Example:
document.write(Math.cos (3))

 sin:

 It returns the value of sine of a number.


 It returns the numeric value between -1 to 1.

Syntax:
Math.sin(number)

Example:
document.write(Math.sin (3))

 tan:
 It returns the number that represents tangent of an angle.
Syntax:
Math.tan(number)

Example:
document.write(Math.tan (1))

 log:
 It returns the natural log (base E) of number.
 If the number is negative(-), NaN is returned.
Syntax:
Math.log(number)

Example:
document.write(Math.log(1))

 pow:
 It returns the value of X to power of Y.
Syntax:
Math.pow(x,y)

Example:
document.write(Math.pow(2,3));

document.write(Math.pow(5,2));

 random:
 It returns a random number between 0 to 1.
Syntax:
Math.random()

Example:
document.write(Math.random());

 max:
 It returns the number with highest value of two specified numbers.

Syntax:
Math.max(x,y)

Example:
document.write(Math.max(10,15));
 min:
 It returns the number with lowest value of two specified numbers.
Syntax:
Math.min(x,y)

Example:
document.write(Math.min(10,15));

 round:
 It rounds the number to nearest integer.
Syntax:
Math.round(number)

Example:
document.write(Math.round(0.60));

document.write(Math.round(0.49));

 sqrt:
 It returns the square root of a number.
Syntax:
Math.sqrt(number)

Example:
document.write(Math.sqrt(16));

Array Object

An array is the collection of elements having similar datatypes or we can say that array provides
the facility to store multiple values in single variable name.

Property:

 length:
 It returns the length of the Array.
Syntax:
ArrayObject.length

Example:
<script languagae=”javacript”>

Var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”
arr[2] = “VB”

document.write(subArr.length)

</script>

Output:
3

Methods:

 concat():
 It is used to join two or more Arrays.
 This method does not change the original arrays.
 It only returns a copy of joined arrays.
Syntax:
ArrayObject.concat()

Example:
<script languagae=”javacript”>

var subArr = new Array()

subArr[0] = “PHP”

subArr [1] = “C”

subArr [2] = “VB”

var moreArr = new Array()

moreArr[0] = “Java”

moreArr[1] = “Oracle”

document.write(subArr.concat(moreArr))
document.write(subArr.length)

</script>
Output:
PHP,C,VB,Java,Oracle

 join():
 It is used to put all the elements of array into string.
 The elements will be seprated by Seprator, comma(,) is default if you omitted the
parameter.
Syntax:
ArrayObject.join(seprator)

Example:

<script languagae=”javacript”>

Var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.join(“:”))

</script>

Output:
PHP: C :VB

 pop():
 It is used to remove and return “Last Element” of Array.
 This method changes the length of original Array.

Syntax:
ArrayObject.pop()

Example:

<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”
arr[1] = “C”

arr[2] = “VB”

document.write(subArr.pop())

</script>

Output:
VB

 shift():
 It is used to remove and return “First Element” of Array.
 This method changes the length of original Array.

Syntax:
ArrayObject.shift()

Example
<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.shift())

</script>

Output:
PHP

 push():
 It is used to add one or more elements to end of the Array and returns new length.

Synatx:
ArrayObject.push(newElement1,newElement2,…)
Example:
<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.push(“java”))

</script>

Output:
4

 unshift():
 It is used to add one or more elements to the beginning of the Array and returns
new length.

Syntax:
ArrayObject.unshift(newElement1,newElement2,…)

Example:
<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.unshift(“oracle”))

</script>

 Output:
4

 reverse():
 It is used to reverse the order of elements in Array.
 It changes the original Array.
Syntax:
ArrayObject.reverse()

Example:
<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.reverse())

</script>

Output:
VB,C,PHP

 slice():
 Its is used to extract a section of an Arrya and returns a new Array.
Syntax:
ArrayObject.slice(start_index,end_index)

Example:
<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.slice(0,1))

</script>

Output:
PHP

 sort():
 It is used to sort the elements of an Array.
 This method wil sort the elements alphabetically by default.
 Numbers will not be sorted correctly.
 To sort numbers, we must create function that compare numbers.
 After sort() method, Array is changed.

Syntax:
ArrayObject.sort()

Example:
<script languagae=”javacript”>

var subArr = new Array()

arr[0] = “PHP”

arr[1] = “C”

arr[2] = “VB”

document.write(subArr.sort())

</script>

Output:
C,PHP,VB

DATE OBJECT:
Javascript does not have the datatype as Date.
However, we can use Date object & its methods to work with dates and times.
Some important things about methods of date object.
Seconds & minutes 0 to 59
Hours 0 to 23
Day 0(Sunday) to 6(Saturday)
Date 1 to 31
Month 0(January) to 11 (December)
Year Years since 1900
Methods:

 Date()
o This method returns today’s date and time.
Syntax:
dateObject.Date()
Example:
Var d=new Date()
document.write(d.Date())

 getDate()
o The getDate() method returns the day of the month.
o The value returned by getDate() us a number between 1 and 31.
o This method is always used in conjunction with a Date object.
Syntax:
dateObject.getDate()
Example:
Var d=new Date()
document.write(d.getDate())

 getDay()
o The getDay() method returns a number that represents the day of the week.
o The value returned by getDay() is a number between 0 and 6. Sunday is 0,
Monday is 1 and so on..
o This method is always used in conjunction with a Date.
Syntax:
dateObject.getDay()
Example:
Var d=new Date()
document.write(d.getDay())

 getMonth()
o The getMonth() method reurns the month as a number.
o The value returned by the getMonth() is a number between 0 and 11. January is 0
and February is 1 and so on..
o This method is always used in conjunction with a Date object.
Syntax:
dateObject.getMonth()
Example:
Var d=new Date()
document.write(d.getMonth())

 getYear()
o The getYear() method returns the month, as a number.
o The value returned by getMonth() is a number between 0 & 11. January is 0,
February is 1 and So on…
o This method is always used in conjunction with date object.
Syntax:
dateObjecct.getYear()

Example:
Var d=new Date()
Document.write(d.getYear())

 getFullYear()
o The getFullYear() method returns a four digit number that represents a year.
o This method is always used in conjunction with a date object.
Syntax:
dateObject.getFullYear()
Example:
Var d=new Date()
Document.write(d.getFullYear())

 getHours()
o The getHours() method returns the hour of a time.
o The value returned by this method is a number that represents the Hour of a day.
o This method is always used in conjunction with date object.
Syntax:
dateObject.getHours()
Example:
Var d=new Date()
Document.write(d.getHours())

 getMinutes()
o The getMinutes() method returns the minutes of a time.
o The value returned by the getMinutes() is a number that represents minutes of a
current Hour.
o This method is used with conjunction with the date object.

Syntax:
dateObject.getMinutes()
Example:
Var d=new Date()
Document.write(d.getMinutes())
getSeconds()
o This method returns the seconds of a time.
o The value returned by this method is a number that represents the second of a
current time.
o This method is always used in conjunction with date object.
Syntax:
dateObject.getSeconds()
Example:
Var d=new Date()
Document.write(d.getSeconds())

 getMilliseconds()
o The getMilliseconds() returns the milliseconds of a time.
o The value returned by this method is a number that represents a milliseconds of a
current time.
o This method is always used in conjunction with date object.
Syntax:
Dateobject.getMilliseconds()
Example:
Var d=new Date()
Document.write(d.getMilliseconds())

 getTime()
o The getTime() returns the number of milliseconds since midnight of January 1,
1970.
o This method is always used in conjunction with Date object.
Syntax:
dateObject.getTime()
Example:
Var d=new Date()
Document.write(d.getTime())

 setDate()
o The setDate() method is used to set the day of the month.
o The value set by setDate() is a number between 1 and 31, that represents the day
number of month.
o This method is always used in conjunction with Date object.
Syntax:
dateObject.setDate(day)
Example:
Var d=new Date()
d.setDate(4)

 setMonth()
o The setMonth() method is used to set the month.
o You can set month by specifying the value of month and value of day.
o The month value in setMonth() is a number between 0 and 11. January is 0,
February is 1 and so on… and the day value in setMonth() is a number between 1
and 31, represents the day of month.
o This method is always used in conjunction with Date object.
o Here the parameter day is optional and month is required.
Syntax:
dateObject.setMonth(month,day)

Example:
Var d=new Date()
d.setMonth(8)

 setFullYear()
o The setFullYear() method is used to set the year.
o You can set the year by specifying the year, month and day value.
o The year value represents the four digit value specifies the year.
o The month value represents the number between the 0 and 11 specifies the month.
o The day value represents the number between 1 and 31, specifies the date.
o Here the parameter year is required and month and day are optional.
Syntax:
dateObject.setFullYear(year,month,day)
Example:
Var d=new Date()
d.setFullYear(2009)

 setYear()
o The setYear() method is used to set the year.
o The value set by the setYear() is a numeric value that represents the year value.
o Always used in conjunction with date Object.
Syntax:
dateObject.setYear(year)
Example:
Var d=new Date()
d.setYear(year)

 setHours()
o The setHours() method is used to set the hour of a specified time.
o You can set hours by specifying the values of hours, minutes, seconds and
milliseconds.
o Here the parameter hours is required. Where as minutes, seconds, milliseconds are
optional.
o Always used in conjunction with date object.
Syntax:
dateObject.setHours(hour,minutes,seconds,millisec)
Example:
Var d=new Date()
d.setHours(10)

 setMinutes()
o The setMinutes() method is used to set the minutes of a specified time.
o You can set the minutes by specifying the values of minutes, seconds and
milliseconds.
o Here the parameter minute is required where as seconds and milliseconds are
optional.
o Always used in conjunction with date object.
Syntax:
dateObject.setMinutes(minute,seconds,milliseconds)
Example:
Var d=new Date()
d.setMinutes(20)

 setSeconds()
o The setSeconds() method is used to set the seconds of a specified time.
o You can set the seconds by specifying the values of seconds and milliseconds.
o Here the parameter second is required and millisecond is optional.
o Always used in conjunction with date Object.
Syntax:
dateObject.setSeconds(seconds,milliseconds)
Example:
Var d=new Date()
d.setSeconds(20);

WINDOW OBJECT
When you load your browser application, a window immediately appears. This window is known
as browser window or window in short. You can use JavaScript to open a window, as the result
of a button click or any other operation. Since each window is represented as a distinct window
object, opening a new window actually creates another window object.

CREATE A WINDOW

WindowVar=[window].open(“URL”,”WindowName”, [Window Attributes],height,width)

Window Attribute Description


Toolbar Back, forward and other buttons button
Location Address bar displaying the current URL
Directories What’s new, What’s Cool and other buttons in that row
Status Status bar at the bottom of the window
Menubar Displays menu bar to the window (File, Edit , View…)
Scrollbars Displays scroll bar to the window
Resizable Allows resizing of the window
Width Windows width in pixel
Height Windows height in pixel
Example 1

<html><head>

<script type="text/javascript">

function open_win()

window.open("","my1","menubar,status,toolbar,height=100,width
=500")

window.open("","my2","fullscreen,menubar,status,toolbar")

</script>

</head>

<body>

<form>

<input type=button value="Open Window" onclick="open_win()" />

</form></body></html>

Example 2

<html>

<head>

<script type="text/javascript">

function closeWin()

myWindow.close()
}

</script>

</head>

<body>

<script type="text/javascript">

myWindow=window.open('','','width=200,height=100)

myWindow.document.write("This is 'myWindow'")

</script>

<form>

<input type="button" value="Close 'myWindow'"


onclick="closeWin()" />

</form>

</body>

</html>

Example 3

<html>

<head>

<script type="text/javascript">

function resizeWindow1()

window.resizeBy(-100,-100)

/*method is used to resize a window by the specified pixels*/


}

function resizeWindow2()

window.resizeTo(500,300)

/*method is used to resize the window to the specified width and height.*/

</script></head>

<body>

<form>

<input type="button" onclick="resizeWindow1()"

value="Resize window By">

<input type="button" onclick="resizeWindow2()"

value="Resize window To">

</form>

</body></html>

HISTORY OBJECT

The browser maintains a list of most recent URL’s, which can be viewed in IE as well as
Netscape. The history list behaves like a LIFO queue (Last In First Out). The history list is
represented in JavaScript by the window.history object. It allows u to deal with list but not with
the data.

History Attribute Description


length[property] Returns the number of elements in the history list
back() Loads the previous URL in the history list
next() Loads the next URL in the history list
go() Loads a specific page in the history list

Example 1

<html>

<head>

<script language = "JavaScript">

function ShowHistory()

alert(" U have accessed " + history.length + " Web Pages ")

</script>

</head>

<body onload="ShowHistory()">

</body>

</html>

Example 2

<html>

<head>

<script type="text/javascript">

function goBack()

history.back()
}

</script>

</head>

<body>

<input type="button"

value="Back"

onclick="goBack()" />

</body>

</html>

Example 3

<html>

<head>

<script type="text/javascript">

function goBack()

history.go(-3)

</script>

</head>

<input type="button" value="Back" onclick="goBack()" />

</html>
LOCATION OBJECT

The Location object is actually a JavaScript object, not an HTML DOM object. The Location
object is automatically created by the JavaScript runtime engine and contains information about
the current URL. Example: Send a user to a new location. The Location object is part of the
Window object and is accessed through the window.location property.IE: Internet Explorer, F:
Firefox, O: Opera.

Location Attribute Description


hash Sets or returns the URL from the hash sign (#)
Sets or returns the hostname and port number of the current
host
URL
hostname Sets or returns the hostname of the current URL
href Sets or returns the entire URL
pathname Sets or returns the path of the current URL
port Sets or returns the port number of the current URL
protocol Sets or returns the protocol of the current URL
search Sets or returns the URL from the question mark (?)
assign() Loads a new document
reload() Reloads the current document
replace() Replaces the current document with a new one

assign()
Example 1

<html>

<head>

<script type="text/javascript">

function newDoc()

window.location.assign("http://www.yahoo.com")

</script>

</head>
<body>

<input type="button"

value="Load new document"

onclick="newDoc()" />

</body></html>

reload()
Example 2

<html>

<head>

<script type="text/javascript">

function reloadPage()

window.location.reload()

</script>

</head>

<body>

<input type="button"

value="Reload page"

onclick="reloadPage()" />

</body>

</html>
replace()
Example 3

<html>

<head>

<script type="text/javascript">

function replaceDoc()

window.location.replace("http://www.yahoo.com")

</script>

</head>

<body>

<input type="button"

value="Replace document"

onclick="replaceDoc()" />

</body>

</html>

Search property
Example 4
<html>

<body>

<script type="text/javascript">

document.write(location.search);

</script>

</body>

</html>

Href property
Example 5

<html>

<body>

<script type="text/javascript">

document.write(location.href);

</script>

</body>

</html>

NAVIGATOR OBJECT

The Navigator object is actually a JavaScript object, not an HTML DOM object. The Navigator
object is automatically created by the JavaScript runtime engine and contains information about
the client browser. IE: Internet Explorer, F: Firefox, O: Opera.
Navigator Attribute Description
appCodeName Returns the code name of the browser
appMinorVersion Returns the minor version of the browser
appName Returns the name of the browser
appVersion Returns the platform and version of the browser
browserLanguage Returns the current browser language
cookieEnabled Returns a Boolean value that specifies whether cookies are
enabled in the browser
cpuClass Returns the CPU class of the browser's system
onLine Returns a Boolean value that specifies whether the system is
in offline mode
platform Returns the operating system platform
systemLanguage Returns the default language used by the OS
userAgent Returns the value of the user-agent header sent by the client
to the server
userLanguage Returns the OS' natural language setting
javaEnabled() Specifies whether or not the browser has Java enabled
taintEnabled() Specifies whether or not the browser has data tainting
enabled

Example

<html>

<body>

<script type="text/javascript">

document.write("<p>Browser: ")

document.write(navigator.appName + "</p>")

document.write("<p>Browserversion: ")

document.write(navigator.appVersion + "</p>")

document.write("<p>Code: ")

document.write(navigator.appCodeName + "</p>")

document.write("<p>Platform: ")

document.write(navigator.platform + "</p>")

document.write("<p>Cookies enabled: ")


document.write(navigator.cookieEnabled +"</p>")

document.write("<p>Browser's useragent header")

document.write(navigator.userAgent + "</p>")

</script>

</body>

</html>

1.15 USER DEFINED OBJECT


 Javascript allows you to create “USER DEFINED OBJECT”.
 A User Defined Object will also be associated with properties and methods.
 For Example:
o A person is an object. The Properties of person’s include name, height, weight,
age etc. All persons have these properties but the values of those properties will
differ from person to person. The person’s methods could be eat(), sleep(),
work(), play() etc.
 There are different ways to create new Object.
o Create an Object with direct initialization of Properties.
o Create a direct instance of Object.
o Create a template of an Object.

Create a direct instance of an object

Example

<html>

<body>

<script language="javascript">

myobj = new Object();

myobj.subject = "Web development"

myobj.part1="Dhtml"

myobj.part2="Javascript"
myobj.part3="Php and Mysql"

document.write(myobj.subject+"<br>")

document.write(myobj.part1+"<br>")

document.write(myobj.part2+"<br>")

document.write(myobj.part3+"<br>")

</script>

</body>

</html>

Create a template of an object

Example

<html>

<body>

<script language="javascript">

function myobject(subject,part1,part2,part3)

this.subject = subject

this.part1= part1

this.part2= part2

this.part3= part3}

myobj = new myobject("Web development","Dhtml","JavaScript","Php &


Mysql");
document.write(myobj.subject+"<br>")

document.write(myobj.part1+"<br>")

document.write(myobj.part2+"<br>")

document.write(myobj.part3+"<br>")

</script>

</body>

</html>

1.16 WORK WITH FORMS IN JAVASCRIPT


There are Two Methods in Document Object Model

1. getElementById()
2. getElementByName()
3. innerHTML property

getElementById()

 If you want to quickly access the value of an HTML input, than these method can
be used.
 It return a reference of the HTML element(control).

Syntax:

getElementById(Control Reference);

For example:

<head>

<script language=javascript>
Function notEmpty()

var mytextfield=document.getElementById(“mytext”);

if(mytextfield.value!=” “)

alert(“You entered”+mytextfield.value);

else

alert(“Would you please enter some text?”);

</script>

<body>

<form>

<input type=text id=”mytext”>

<input type=button onClick=notEmpty() value=”Form Checker”>

</form>

</body></script>

 Here document.getElementById returned a reference to our HTML element


mytext.
 We stored this reference into a variable, mytextfield, and then used the value
property that all input elements have to use to grab the value the user enters.
 getElementById is a method or a function of the document object. This means you
can only access it by using document.getElementById.
getElementByName()

 It returns a collection of an objects with the specified NAME.

Syntax:

document.getElementByName(Name);

for example:

<head>

<script language=javascript>

function getElements()

var x=document.getElementByName(“myinput”);

alert(x.length);

</script>

</head>

<body>

<form>

<input type=text name=”myinput”>;

<input type=text name=”myinput”>;

<input type=text name=”myinput”>;

<input type=button onClick=getElements() value=”How many Elements named


MyInputs”>
</form>

</script>

</body>

innerHTML property

 The innerHTML property sets or returns the HTML content (inner HTML) of an
element.

Syntax

Return the innerHTML property:

HTMLElementObject.innerHTML

Set the innerHTML property:

HTMLElementObject.innerHTML=text

for Example

<body>

Web Scripting Language!<span id="mytext"


onmouseover=f()>javascript</span>

</body>

<head>

<script type="text/javascript">

function f()

document.getElementById("mytext").innerHTML="JavaScript";

}
</script>

</head>

THE JAVASCRIPT DOCUMENT OBJECT MODEL

 Every web page resides inside a browser window which can be considered as an
object.
 A Document object represents the HTML document that is displayed in that window.
The Document object has various properties that refer to other objects which allow
access to and modification of document content.
 The way that document content is accessed and modified is called the Document
Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web document.
o Window object: Top of the hierarchy. It is the outmost element of the object
hierarchy.
o Document object: Each HTML document that gets loaded into a window becomes a
document object. The document contains the content of the page.
o Form object: Everything enclosed in the <form>...</form> tags sets the form object.
o Form control elements: The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.
o Here is a simple hierarchy of few important objects:
o There are several DOMs in existence. The following sections explain each of these
DOMs in detail and describe how you can use them to access and modify document
content.
 The Legacy DOM: This is the model which was introduced in early versions
of JavaScript language. It is well supported by all browsers, but allows access
only to certain key portions of documents, such as forms, form elements, and
images.
 The W3C DOM: This document object model allows access and
modification of all document content and is standardized by the World Wide
Web Consortium (W3C). This model is supported by almost all the modern
browsers.
 The IE4 DOM: This document object model was introduced in Version 4 of
Microsoft's Internet Explorer browser. IE 5 and later versions include support
for most basic W3C DOM features.

THE LEGACY DOM:


 This is the model which was introduced in early versions of JavaScript
language. It is well supported by all browsers, but allows access only to
certain key portions of documents, such as forms, form elements, and images.
 This model provides several read-only properties, such as title, URL, and
lastModified provide information about the document as a whole. Apart from
that there are various methods provided by this model which can be used to
set and get document property values.

DOCUMENT PROPERTIES IN LEGACY DOM:


 Here is the list of document properties which can be accessed using Legacy
DOM:

Property Description & Example

alinkColor Deprecated - A string that specifies the color of activated


links. Example: document.alinkColor

anchors[ ] An array of Anchor objects, one for each anchor that


appears in the document
Example: document.anchors[0], document.anchors[1] and
so on

applets[ ] An array of Applet objects, one for each applet that


appears in the document
Example: document.applets[0], document.applets[1] and
so on
bgColor Deprecated - A string that specifies the background color
of the document.
Example: document.bgColor

Cookie A string-valued property with special behavior that


allows the cookies associated with this document to be
queried and set.
Example: document.cookie

Domain A string that specifies the Internet domain the document


is from. Used for security purpose.
Example: document.domain

embeds[ ] An array of objects that represent data embedded in the


document with the <embed> tag. A synonym for plugins[
]. Some plugins and ActiveX controls can be controlled
with JavaScript code.
Example: document.embeds[0], document.embeds[1] and
so on

fgColor Deprecated - A string that specifies the default text color


for the document
Example: document.fgColor

forms[ ] An array of Form objects, one for each HTML form that
appears in the document.
Example: document.forms[0], document.forms[1] and so
on

images[ ] An array of Image objects, one for each image that is


embedded in the document with the HTML <img> tag.
Example: document.images[0], document.images[1] and
so on

lastModified A read-only string that specifies the date of the most


recent change to the document
Example: document.lastModified

linkColor Deprecated - A string that specifies the color of


unvisited links
Example: document.linkColor

links[ ] links[ ]
Example: document.links[0], document.links[1] and so
on

Location The URL of the document. Deprecated in favor of the


URL property.
Example: document.location

plugins[ ] A synonym for the embeds[ ]


Example: document.plugins[0], document.plugins[1] and
so on

Referrer A read-only string that contains the URL of the


document, if any, from which the current document was
linked.
Example: document.referrer

Title The text contents of the <title> tag.


Example: document.title

URL A read-only string that specifies the URL of the


document.
Example: document.URL

vlinkColor Deprecated - A string that specifies the color of visited


links.
Example: document.vlinkColor

DOCUMENT METHODS IN LEGACY DOM:


 Here is the list of methods supported by Legacy DOM:

Property Description & Example

clear( ) Deprecated - Erases the contents of the


document and returns nothing.
Example: document.clear( )

close( ) Closes a document stream opened with the


open( ) method and returns nothing.
Example: document.close( )

open( ) Deletes existing document content and


opens a stream to which new document
contents may be written. Returns nothing.
Example: document.open( )

write( value, ...) Inserts the specified string or strings into


the document currently being parsed or
appends to document opened with open( ).
Returns nothing.
Example: document.write( value, ...)

Identical to write( ), except that it appends a


newline character to the output. Returns
nothing.
Example: document.writeln( value, ...)
writeln( value, ...)

EXAMPLE
o We can locate any HTML element with-in any HTML document using HTML DOM. For
instance, if a web document contains a form element then using JavaScript we can refer
to it as document.forms[0]. If your Web document includes two form elements the first
form is referred to as document.forms[0] and the second document.forms[1].

o Using the hierarchy and properties given above, we can access first form element using
document.forms[0].elements[0] and so on.
o Here is an example to access document properties using Legacy DOM method:

<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
function myFunc()
{
var ret = document.title;
alert("Document Title : " + ret );

var ret = document.URL;


alert("Document URL : " + ret );

var ret = document.forms[0];


alert("Document First Form : " + ret );

var ret = document.forms[0].elements[1];


alert("Second element : " + ret );

THE}W3C DOM
</script>
o This document object model allows access and modification of all document content
</head>
and is standardized by the World Wide Web Consortium (W3C). This model is
<body>
supported by almost all the modern browsers.
<h1 id="title">This is main title</h1>
o The W3Cthe
<p>Click DOM standardizes
following most
to see the of the features of the legacy DOM, but also adds
result:</p>
important new ones. In addition to supporting forms[ ], images[ ], and other array
<form name="FirstForm">
properties of the Document object, it defines methods that allow scripts to access and
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
manipulate any document element and not just special-purpose elements like forms
and images.
DOCUMENT PROPERTIES IN W3C DOM:
This model supports all the properties available in Legacy DOM.
Additionally, here is the list of document properties which can be accessed
using W3C DOM:

Property Description & Example

Body A reference to the Element object that


represents the <body> tag of this document.
Example: document.body

defaultView Its Read-only property and represents the


window in which the document is displayed.
Example: document.defaultView

documentElement A read-only reference to the <html> tag of


the document.
Example:
document.documentElement8/31/2008

Implementation Its Read-only property and represents the


DOMImplementation object that represents
the implementation that created this
document.
Example: document.implementation

DOCUMENT METHODS IN W3C DOM:


This model supports all the methods available in Legacy DOM. Additionally, here is
the list of methods supported by W3C DOM:

Property Description & Example

createAttribute( name) Returns a newly-created Attr node with the


specified name.
Example: document.createAttribute( name)

createComment( text) Creates and returns a new Comment node


containing the specified text.
Example: document.createComment( text)

createDocumentFragment( ) Creates and returns an empty


DocumentFragment node.
Example:
document.createDocumentFragment( )
createElement( tagName) Creates and returns a new Element node with
the specified tag name.
Example: document.createElement( tagName)

createTextNode( text) Creates and returns a new Text node that


contains the specified text.
Example: document.createTextNode( text)

getElementById( id) Returns the Element of this document that has


the specified value for its id attribute, or null if
no such Element exists in the document.
Example: document.getElementById( id)

getElementsByName( name) Returns an array of nodes of all elements in


the document that have a specified value for
their name attribute. If no such elements are
found, returns a zero-length array.
Example:
document.getElementsByName( name)

getElementsByTagName( tagname) Returns an array of all Element nodes in this


document that have the specified tag name.
The Element nodes appear in the returned
array in the same order they appear in the
document source.
Example: document.getElementsByTagName(
tagname)

importNode( importedNode, deep) Creates and returns a copy of a node from


some other document that is suitable for
insertion into this document. If the deep
argument is true, it recursively copies the
children of the node too. Supported in DOM
Version 2
Example:
document.importNode( importedNode, deep)

EXAMPLE
o This is very easy to manipulate ( Accessing and Setting ) document element using
W3C DOM. You can use any of the methods like getElementById,
getElementsByName, or getElementsByTagName.

o Here is an example to access document properties using W3C DOM method:

<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
function myFunc()
THE IE 4 DOM

o This document object model was introduced in Version 4 of Microsoft's Internet


Explorer browser. IE 5 and later versions include support for most basic W3C DOM
features.
o DOCUMENT PROPERTIES IN IE 4 DOM:
o The following non-standard (and non-portable) properties are defined by Internet
Explorer 4 and later versions.

Property Description & Example

activeElement A read-only property that refers to the input element that is


currently active (i.e., has the input focus).
Example: document.activeElement

all[ ] An array of all Element objects within the document. This array
may be indexed numerically to access elements in source order, or
it may be indexed by element id or name.
Example: document.all[ ]

Charset The character set of the document.


Example: document.charset

children[ ] An array that contains the HTML elements that are direct children
of the document. Note that this is different than the all[ ] array
that contains all elements in the document, regardless of their
position in the containment hierarchy.
Example: document.children[ ]

defaultCharset The default character set of the document.


Example: document.defaultCharset

Expando This property, if set to false, prevents client-side objects from


being expanded.
Example: document.expando

parentWindow The window that contains the document.


Example: document.parentWindow

readyState Specifies the loading status of a document. It has one of the


following four string values:
Example: document.readyState

Uninitialized The document has not started loading.


Example: document.uninitialized

Loading The document is loading.


Example: document.loading

Interactive The document has loaded sufficiently for the user to interact with
it.
Example: document.interactive

Complete The document is completely loaded.


Example: document.complete

DOCUMENT METHODS IN IE4 DOM:


This model supports all the methods available in Legacy DOM. Additionally, here is the
list of methods supported by IE4 DOM:

Property Description & Example

elementFromPoint(x,y) Returns the Element located at a


specified point.
Example: document.elementFromPoint(x,y)

EXAMPLE:
o The IE 4 DOM does not support the getElementById( ) method. Instead, it allows you to
look up arbitrary document elements by id attribute within the all[ ] array of the
document object.
o Here's how to find all <li> tags within the first <ul> tag. Note that you must specify the
desired HTML tag name in uppercase with the all.tags( ) method.
var lists = document.all.tags("UL");

var items = lists[0].all.tags("LI");

o Here is another example to access document properties using IE4 DOM method:

<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
function myFunc()
{
var ret = document.all["heading"];
alert("Document Heading : " + ret.innerHTML );
BUILT IN OBJECTS IN JAVASCRIPT
COOKIES
Cookies are data, stored in small text files, on your computer.Web Browser and Server use
HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial
website it is required to maintain session information among different pages.

HOW IT WORKS
 Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on your site, the browser sends the
same cookie to the server for retrieval. Once retrieved, your server knows/remembers
what was stored earlier.
 Cookies are a plain text data record of 5 variable-length fields:
 Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
 Domain: The domain name of your site.
 Path: The path to the directory or web page that set the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
 Secure: If this field contains the word "secure" then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
 Name=Value: Cookies are set and retrieved in the form of key and value
pairs.
 Cookies were originally designed for CGI programming and cookies' data is
automatically transmitted between the web browser and web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
 JavaScript can also manipulate cookies using the cookie property of the Document
object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to
the current web page.

STORING COOKIES:
 The simplest way to create a cookie is to assign a string value to the document.cookie
object, which looks like this:
SYNTAX
document.cookie = "key1=value1;key2=value2;expires=date";

 Here expires attribute is option. If you provide this attribute with a valid date or time
then cookie will expire at the given date or time and after that cookies' value will not
be accessible.
EXAMPLE
<html>
<head>
<script type="text/javascript">
function WriteCookie()
READING COOKIES
{
 Reading a cookie is just as simple==as"" writing
if( document.myform.customer.value ){ one, because the value of the
document.cookie object
alert("Enter some is the cookie. So you can use this string whenever you want
value!");
return;
to access the cookie.
 The} document.cookie string will keep a list of name=value pairs separated by
semicolons, where name is the name of a cookie and value is its string value.
cookievalue= escape(document.myform.customer.value) + ";";
EXAMPLE
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
<html>
}<head>
<script type="text/javascript">
</script>
function ReadCookie()
</head>
{
<body>
var allcookies = document.cookie;
<form name="myform"
alert("All Cookies : " + action="">
allcookies );
Enter name: <input type="text" name="customer"/>
<input
// Gettype="button"
all the cookiesvalue="Set
pairs in anCookie"
array onclick="WriteCookie();"/>
</form>
cookiearray = allcookies.split(';');
</body>
</html>
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
</script>
</head>
<body>
SETTING THE COOKIES EXPIRATION DATE
 You can extend the life of a cookie beyond the current browser session by setting an
expiration date and saving the expiration date within the cookie. This can be done by
setting the expires attribute to a date and time.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

DELETING A COOKIE:
 Sometimes you will want to delete a cookie so that subsequent attempts to read the
cookie return nothing. To do this, you just need to set the expiration date to a time in
the past.
EXAMPLE:

The following example illustrates how to delete cookie by setting expiration date one
Month in past :
<html>
<head>
<script type="text/javascript">
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
</script>
Writing Server Side Script
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

2. WRITING SERVER-SIDE SCRIPT

2.1 INTRODUCTION TO PHP


 PHP (Hypertext Pre-Processor) is a server-side web programming language that is
widely used for web development.
 The full from of PHP is “Hypertext Preprocessor”. Its original name was “personal
Home page”.
 Rasmus Lerdorf software engineer, Apache team member is the creator and original
driving force behind PHP. The first part of PHP was developed for his personal use in
late 1994.
 By the middle of 1997, PHP was being used on approximately 50,000 sites
worldwide.
 PHP is server-side scripting language, which can be embedded in HTML or Used as a
stand-alone.
 PHP doesn’t do anything about what a page looks and sound like. In fact of what PHP
does is invisible to the end user.
 PHP is an official module of Apache HTTP Server.

ADVANTAGES OF PHP
 Cost: PHP costs you nothing. It is open source software and doesn’t need to purchase
it for development.
 Ease to use: PHP is easy to learn, compared to the others. A lot of Ready-made PHP
scripts are freely available in market so, you can use them in your project or get some
help from them.
 HTML – Support: PHP is embedded within HTML; In other words, PHP pages are
ordinary HTML pages that escape into PHP mode only when necessary. When a
client requests this page, the web server preprocesses it. This means it goes through
the page from top to bottom, looking for sections of PHP, which it will try to resolve.
 Cross-platform Compatibility: PHP and MySQL run native on every popular flavor
of Unix and Windows. A huge percentage of the world’s HTTP servers run on one of
these two classes of operating system.
 PHP is compatible with the three leading Web server: Apache HTTP Server for Unix
and windows. Microsoft Internet Informing Server (IIS), and Netscape Enterprise
Server, It Also works with several lesser-known servers, including Alex Blits’
fhttpd, Microsoft’s Personal Web server, AOL Server and Omnicentrix’s Omni server
application server.
 Stability : The word stable means two different things in this context :
 The server doesn’t need to be rebooted often
 The software doesn’t change radically and incompatibly from release to
release.
To our advantage, both of these apply to both MySQL and PHP.
 Speed: PHP is pleasingly zippy in its execution, especially when compiled as and
Apache module of the UNIX side. Although it takes a slight performance his by being
interpreted rather than compiled, this is far outweighed by benefits PHP drives from
its status as a Web server module.

DIS-ADVANTAGES OF PHP

 Security :
Since it is open sourced, so all people can see the source code, if there are bugs in the
source code, it can be used by people to explore the weakness of PHP.
 Not suitable for large applications:
Hard to maintain since it is not very modular.
 Weak type:
Implicit conversion may surprise unwary programmers and lead to unexpected bugs.
For example, the strings “1000” and “1e3” compare equal because they are implicitly
cast to floating point numbers.

HOW PHP WORKS


 The PHP software works with the web server, which is the software that delivers web
pages to the world. When you type a URL into your web browser’s address bar,
you’re sending a message to the web server at that URL, asking it to send you an
HTML file. The web server responds by sending the requested file. Your browser
reads the HTML file and displays the web page.
 You also request a file from the web server when you click a link in a web page. In
addition, the web server processes a file when you click a web page button that
submits a form. This process is essentially the same when PHP is installed. You
request a file, the web server happens to be running PHP, and it sends HTML back to
the browser, thanks to the programming in PHP.
 More specifically, when PHP is installed, the web server is configured to expect
certain file extensions to contain PHP language statements. Often the extension
is .php or .phtml, but any extension can be used. When the web server gets a request
for a file with the designated extension, it sends the HTML statements as is, but PHP
statements are processed by the PHP software before they’re sent to the requester.
 When PHP language statements are processed, only the output, or anything printed to
the screen is sent by the web server to the web browser. The PHP language
statements, those that don't produce any output to the screen, aren’t included in the
output sent to the browser, so the PHP code is not normally seen by the user.
 For instance, in this simple PHP statement, <?php is the PHP opening tag, and ?> is the
closing tag. <?php echo "<p>Hello World</p>"; ?> Here, echo is a PHP instruction that
tells PHP to output the upcoming text. The PHP software processes the PHP statement
and outputs the following:
<p>Hello World</p>
 That regular HTML statement is delivered to the user’s browser. The browser interprets
the statement as HTML code and displays a web page with one paragraph — Hello
World. The PHP statement isn’t delivered to the browser, so the user never sees any PHP
statements. PHP and the web server must work closely together.
 PHP isn’t integrated with all web servers but does work with many of the popular web
servers. PHP works well with the Apache web server. PHP also works with Microsoft
Internet Information Services (IIS) and others.

THE PHP .INI FILE


 The PHP configuration file, php.ini, is the final and most immediate way to affect
PHP's functionality. The php.ini file is read each time PHP is initialized. in other
words, whenever httpd is restarted for the module version or with each script
execution for the CGI version. If your change isn’t showing up, remember to stop and
restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini.
 The configuration file is well commented and thorough. Keys are case sensitive,
keyword values are not; whitespace, and lines beginning with semicolons are ignored.
Booleans can be represented by 1/0, Yes/No, On/Off, or True/False. The default
values in php.ini-dist will result in a reasonable PHP installation that can be tweaked
later
 Here we are explaining the important settings in php.ini which you may need for your
PHP Parser.

o short_open_tag = Off
Short open tags look like this: <? ?>. This option must be set to Off if you want to use
XML functions

o safe_mode = Off
If this is set to On, you probably compiled PHP with the --enable-safe-mode flag.
Safe mode is most relevant to CGI use. See the explanation in the section "CGI
compile-time options". earlier in this chapter.

o safe_mode_exec_dir = [DIR]
This option is relevant only if safe mode is on; it can also be set with the --with-exec-
dir flag during the Unix build process. PHP in safe mode only executes external
binaries out of this directory. The default is /usr/local/bin. This has nothing to do with
serving up a normal PHP/HTML Web page.

o safe_mode_allowed_env_vars = [PHP_]
This option sets which environment variables users can change in safe mode. The
default is only those variables prepended with "PHP_". If this directive is empty,
most variables are alterable.

o safe_mode_protected_env_vars = [LD_LIBRARY_PATH]
This option sets which environment variables users can't change in safe mode, even if
safe_mode_allowed_env_vars is set permissively

o disable_functions = [function1, function2...]


A welcome addition to PHP4 configuration and one perpetuated in PHP5 is the ability
to disable selected functions for security reasons. Previously, this necessitated hand-
editing the C code from which PHP was made. Filesystem, system, and network
functions should probably be the first to go because allowing the capability to write
files and alter the system over HTTP is never such a safe idea.

o max_execution_time = 30
The function set_time_limit() won.t work in safe mode, so this is the main way to
make a script time out in safe mode. In Windows, you have to abort based on
maximum memory consumed rather than time. You can also use the Apache timeout
setting to timeout if you use Apache, but that will apply to non-PHP files on the site
too.
o error_reporting = E_ALL & ~E_NOTICE
The default value is E_ALL & ~E_NOTICE, all errors except notices. Development
servers should be set to at least the default; only production servers should even
consider a lesser value
o error_prepend_string = [""]
With its bookend, error_append_string, this setting allows you to make error
messages a different color than other text, or what have you.

o warn_plus_overloading = Off
This setting issues a warning if the + operator is used with strings, as in a form value.

o variables_order = EGPCS
This configuration setting supersedes gpc_order. Both are now deprecated along with
register_globals. It sets the order of the different variables: Environment, GET,
POST, COOKIE, and SERVER (aka Built-in).You can change this order around.
Variables will be overwritten successively in left-to-right order, with the rightmost
one winning the hand every time. This means if you left the default setting and
happened to use the same name for an environment variable, a POST variable, and a
COOKIE variable, the COOKIE variable would own that name at the end of the
process. In real life, this doesn't happen much.

o register_globals = Off
This setting allows you to decide whether you wish to register EGPCS variables as
global. This is now deprecated, and as of PHP4.2, this flag is set to Off by default.
Use superglobal arrays instead. All the major code listings in this book use
superglobal arrays.

o gpc_order = GPC
This setting has been GPC Deprecated.

o magic_quotes_gpc = On
This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of
forms which possibly submit to themselves or other forms and display form values,
you may need to set this directive to On or prepare to use addslashes() on string-type
data.

o magic_quotes_runtime = Off
This setting escapes quotes in incoming database and text strings. Remember that
SQL adds slashes to single quotes and apostrophes when storing strings and does not
strip them off when returning them. If this setting is Off, you will need to use
stripslashes() when outputting any type of string data from a SQL database. If
magic_quotes_sybase is set to On, this must be Off.
o magic_quotes_sybase = Off
This setting escapes single quotes in incoming database and text strings with Sybase-
style single quotes rather than backslashes. If magic_quotes_runtime is set to On, this
must be Off.

o auto-prepend-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the beginning of
every PHP file. Include path restrictions do apply.

o auto-append-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the end of every
PHP file.unless you escape by using the exit() function. Include path restrictions do
apply.

o include_path = [DIR]
If you set this value, you will only be allowed to include or require files from these
directories. The include directory is generally under your document root; this is
mandatory if you.re running in safe mode. Set this to . in order to include files from
the same directory your script is in. Multiple directories are separated by colons:
.:/usr/local/apache/htdocs:/usr/local/lib.

o doc_root = [DIR]
If you.re using Apache, you.ve already set a document root for this server or virtual
host in httpd.conf. Set this value here if you.re using safe mode or if you want to
enable PHP only on a portion of your site (for example, only in one subdirectory of
your Web root).

o file_uploads = [on/off]
Turn on this flag if you will upload files using PHP script.

o upload_tmp_dir = [DIR]
Do not uncomment this line unless you understand the implications of HTTP uploads!

o session.save-handler = files
Except in rare circumstances, you will not want to change this setting. So don't touch
it.

o ignore_user_abort = [On/Off]
This setting controls what happens if a site visitor clicks the browser.s Stop button.
The default is On, which means that the script continues to run to completion or
timeout. If the setting is changed to Off, the script will abort. This setting only works
in module mode, not CGI.

o mysql.default_host = hostname
The default server host to use when connecting to the database server if no other host
is specified.

o mysql.default_user = username
The default user name to use when connecting to the database server if no other name
is specified.

o mysql.default_password = password
The default password to use when connecting to the database server if no other
password is specified.

o upload_max_filesize = 10M
The maximum size of an uploaded file.

o memory_limit
This sets the maximum amount of memory in bytes that a script is allowed to allocate.
This helps prevent poorly written scripts for eating up all available memory on a
server. Note that to have no memory limit, set this directive to -1.

o post_max_size = 10M
Sets max size of post data allowed. This setting also affects file upload. To upload
large files, this value must be larger than upload_max_filesize. If memory limit is
enabled by your configure script, memory_limit also affects file uploading. Generally
speaking, memory_limit should be larger than post_max_size.

2.2 BASIC PHP SYNTAX


PHP TAGS

o There are four different pairs of opening and closing tags which can be used in
php. Here is the list of tags.
o Default syntax
o Short open Tags
o HTML Script Tags
o ASP Style Tags
Default Syntax
o The default syntax starts with "<? php" and ends with "?>".
Example
<?php
echo "Default Syntax";
?>

Short open Tags


o The short tags starts with "<?" and ends with "?>". Short style tags are only
available when they are enabled in php.ini configuration file on servers.
Example
<?
echo "PHP example with short-tags";
?>

HTML Script Tags


o HTML script tags look like this
Example
<script language="php">
echo "This is HTML script tags.";
</script>

ASP Style Tags


o The ASP style tags starts with "<%" and ends with "%>". ASP style tags are only
available when they are enabled in php.ini configuration file on servers.
o Note: The above two tags and examples are given only for reference, but not used
in practice any more.
Example
<%
echo 'This is ASP like style';
%>

Comments

PHP has two forms of comments:

 Single-line comments begin with a double slash (//).


 Multi-line comments begin with "/*" and end with "*/".

Syntax
// This is a single-line comment

/*

This is

a multi-line

comment.

*/

VARIABLES in PHP
 A variable is a holder for a type of data. Variable in PHP are represented by a dollar
sing followed by the name of the variable.
 The variable name is case-sensitive.
 Variable naming rule is: A valid variable name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.

Syntax:
$varName = "Value";

CASE SENSITIVITY

o One thing that causes many problems and take hours of finding mistakes is case sensitivity.
PHP is case sensitive.

EXAMPLE

<?php
$myVar = "WebCheatSheet";
$myvar = "PHP tutorial";
echo "$myVar - $myvar"; //outputs "WebCheatSheet - PHP tutorial"
?>

VARIABLE NAMES (IDENTIFIERS)

Variable, function and class names are all identifiers and all follow the rules below, with
the exception that function names are not case sensitive.

 consist of letters, digits, underscores and dollar signs


 cannot begin with a digit
 are case sensitive

TYPE STRENGTH
PHP is weakly typed, meaning that variables do not need to be assigned a type (e.g,
Integer) at the time they are declared. Rather, the type of a PHP variable is determined by
the value the variable holds and the way in which it is used.

Hello Variables!

Here is the "Hello World!" script again, but this time we use a variable.

Code Sample:

<?php
$greeting = 'Hello World!';
?>
<body>
<?php
echo $greeting;
?>
</body>
</html>

This time the string "Hello World!" is stored in the $greeting variable, which is output in
the title and body of the page with an echo command.

VARIABLE SCOPE

A variable's scope determines the locations from which the variable can be accessed. PHP
variables are superglobal, global, or local.

VariableScope Explanation

Superglobal variables are predefined arrays, including $_POST and


Superglobal
$_GET. They are accessible from anywhere on the page.

Global variables are visible throughout the script in which they are
Global declared. However, they are not visible within functions in the script unless
they are re-declared within the function as global variables.

Variables in the function scope are called local variables. Local variables
are local to the function in which they are declared.

SUPERGLOBALS
Again, superglobal variables are predefined arrays, including $_POST and $_GET and
are accessible from anywhere on the page. The complete list of superglobals is shown
below.

 $_GET - variables passed into a page on the query string.


 $_POST - variables passed into a page through a form using the post method.
 $_SERVER - server environment variables (e.g, $_SERVER['HTTP_REFERER']
returns the URL of the referring page).
 $_COOKIE - cookie variables.
 $_FILES - variables containing information about uploaded files.
 $_REQUEST - variables passed into a page through forms, the query string and
cookies.
 $_SESSION - session variables.

The elements within superglobal variables can be accessed in three different ways, which
the authors of PHP and MySQL Web Development refer to as short style, medium style,
and long style.

GLOBALS

o $GLOBALS is a php super global variable which can be used instead of 'global'
keyword to access variables from global scope, i.e. the variables which can be
accessed from anywhere in a php script even within functions or methods.
o EXAMPLE
<?php
$s = 25;
$t = 50;
function subtraction()
{
$GLOBALS['v'] = $GLOBALS['t'] - $GLOBALS['s'];
}
subtraction();
echo $v;
?>

CONSTANTS
o A constant is an identifier for a simple value. The value cannot be modified
during the script's execution. A valid constant name starts with a letter or
underscore (no dollar ($) sign before the name) and by convention constant
identifier are always uppercase.
o Constants are defined by using the define() function or by using the const
keyword outside a class definition.
o The name of the constant and the value must be placed within the parentheses.
After defining it can never be changed or undefined.
o Only scalar data i.e. boolean, integer, float and string can be contained in
constants.
SYNTAX
define(name, value, case-insensitive)

PARAMETERS

name Specifies the name of the constant

value Specifies the value of the constant

case-insensitive Specifies whether the constant name should be case-


insensitive. Default is false

EXAMPLE
<?php
// first we define a constant PASSWORD
define("PASSWORD","admin");

echo (PASSWORD); // will display value of PASSWORD constant, i.e. admin


echo constant("PASSWORD"); // will also display admin
echo "PASSWORD"; // will display PASSWORD
?>
TESTING AND MANIPULATION FUNCTIONS

PHP provides built-in functions for checking if a variable exists, checking if a variable
holds a value, and removing a variable.

To output the results of these functions to a browser, use the var_dump() function (e.g.
var_dump(isset($a));).

unset() : Removes a variable from memory

Example

<?php

$xyz='w3resource.com';

echo 'Before using unset() the value of $xys is : '. $xyz.'<br>';

unset($xyz);

echo 'After using unset() the value of $xys is : '. $xyz;

?>

Var_dump(): returns the type of the variable.

Example

<?php

$var1 = 'test';

var_dump(isset($var1));

?>

Empty() : Checks to see if a variable contains a non-empty, non-false value

Example
<?php
$var = 0;

// Evaluates to true because $var is empty


if (empty($var))

{
echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set


if (isset($var))

{
echo '$var is set even though it is empty';
}
?>

isset() : Checks to see if a variable exists. Returns true or false.

Example

<?php
$var = 0;

// Evaluates as true because $var is set


if (isset($var))

{
echo '$var is set even though it is empty';
}
?>

PHP OPERATORS
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
 Incrementing/Decrementing Operators

ARITHMETIC OPERATORS
 Assume variable $a holds 10 and variable $b holds 20 then:
Operator Description Example

+ Adds two operands $a+$b = 30


- Subtracts second operand from the first $a-$b = -10
* Multiply both operands $a*$b = 200
/ Divide $b/$a =0.5
% Modulus Operator and display remainder $b%$a =1 0
COMPARISON OPERATORS
 Assume variable $a holds 10 and variable $b holds 20 then:

Operator Description Example


== Checks if the value of two operands are equal $a+$b = 30
or not, if yes then condition becomes true
otherwise it will return false
- Subtracts second operand from the first $a-$b = -10
* Multiply both operands $a*$b = 200
/ Divide $b/$a = 2
% Modulus Operator and display remainder $b%$a = 0

LOGICAL (OR RELATIONAL) OPERATORS


 Logical operators first convert their operands to boolean values and then perform the
respective comparison.

Operator Description Example


And Called Logical AND operator. True if both x and x=6
y are true y=3
(x < 10 and y > 1) returns true
or Called Logical OR Operator. True if either or x=6
both x and y are true y=3
(x==6 or y==5) returns true
&& Called Logical AND operator. True if both x and x=6
y are true y=3
(x < 10 && y > 1) returns true
|| Called Logical OR Operator. True if either or x=6
both x and y are true y=3
(x==5 || y==5) returns false
! Called Logical NOT Operator. True if x is not x=6
true y=3
!(x==y) returns true

ASSIGNMENT OPERATORS
 Assignment operators allow writing a value to a variable. The first operand must be a
variable and the basic assignment operator is "=". The value of an assignment
expression is the final value assigned to the variable. In addition to the regular
assignment operator "=", several other assignment operators are composites of an
operator followed by an equal sign.

Operator Work like as Description Example


= a=b Simple assignment operator, Assigns values c=a+b
from right side operands to left side operand
+= a=a+b Add(+) and assignment operator. c+=a;
-= a=a-b Subtract(-) and assignment operator c-=a;
*= a=a*b Multiply and assignment operator c*=a;
/= a=a/b Divide and assignment operator c/=a;
%= a=a%b Modulus and assignment operator c%=a;

CONDITIONAL (OR TERNARY) OPERATORS


 The ternary or conditional operator is a quick way to construct if/else comparison
operations, and it can often reduce four or more lines of code into one short statement.
 The ternary operator is really an alternate (or even shorthand) way of
writing if/else comparison operations

SYNTAX:
The ternary operator in PHP consists of three expressions: a condition, and two operands
that describe what action should be taken if the condition is true or false
$variable = ( condition ) ? true : false;

EXAMPLE:
<?php
$a=10;
$b=20;
$answer = ($a >= $b) ? "Condition is Ture" : "Condition is False";
echo $answer;
?>
Output:
Condition is False
INCREMENTING/DECREMENTING OPERATORS

Assume variable $a holds 10.

Operator Description Example


++x Pre Increment operator, increases integer value by $a++ will give 11
one , then returns x
x++ Returns x, then increases integer value by one. ++$a will give 10
--x Pre Decrement operator, decreases integer value by --$a will give 9
one
x-- Return x, then decreases integer value by one. $a-- will give 10.

PASSING VARIABLES ON THE URL

o There are different ways by which values of variables can be passed between
pages. One of the ways is to use the URL to pass the values or data.
o Here the biggest advantage is we can pass data to a different site even running at
different servers.
o Any scripting language like ASP, JSP, PHP or Perl running at receiving end can
process and collect the value from the query string or from the URL.
o Here one main concern is the data gets exposed in address bar of the browser and
can be easily accessible by using browser history.
o So this is not a good idea to pass sensitive data like password through the URL to
different pages or different sites.

EXAMPLE
<?php
$name='vsc';
echo "<a href='page2.php?user=$name'>link to page1</a>";
?>

o When the above link is clicked, page2.php gets the variables user with variable
$name. Here is the code to collect data in PHP.
EXAMPLE
echo $_GET[user]; // output vsc
FIRST PHP SCRIPT

In this exercise, you will write a simple PHP script from scratch. The script will declare a
variable called $today that stores the day of the week.

1. Open a new document and save it as Today.php in the PhpBasics/Exercises folder.

You must save the file in the c:\XAMPP\htdocs\Webucator\ClassFiles directory path.

2. Declare a variable called $today that holds the current day of the week as literal text.
3. Output $today in the title and body of the page.

4. Test your solution in a browser. The resulting HTML page should look like this:

FLOW CONTROLS
Flow control in PHP with if-elseif-else conditions and with loops.
2.6.1 CONDITIONAL STRUCTURE

 Conditional statements are used to perform different actions based on different


conditions.
o if
o if...else
o if...elseif....else

IF STATEMENT

 Use this statement to execute some code only if a specified condition is true.

SYNTAX:

<?php
if (condition)
statement; //code to be executed if condition is true;
?>

EXAMPLE:

<?php
$a=10;
$b=20;
if ($a<=$b)

echo "A is Less


IF...ELSE than or Equal to B";
STATEMENT
?>
Output:
A is Less than or Equal to B

 Use this statement to execute some code if a condition is true and another code if the
condition is false.

SYNTAX:

<?php
if (condition)
{
statement; //code to be executed if condition is true;
}
else
{
statement; //code to be executed if condition is false;

}
EXAMPLE:

<?php
$a=10;
$b=20;
if ($a==$b)
{
echo "A is Equal to B";
}
else
{
echo "A is Greater than or Equal to B";
}
?>
Output
A is Greater than or Equal to B

IF...ELSEIF....ELSE STATEMENT

 Used with the if...else statement to execute a set of code if one of several condition are
true.

SYNTAX
if (condition)
{
statement; //code to be executed if condition is true;
}
elseif (condition)
{
statement; //code to be executed if condition is true;
}
else EXAMPLE
{
statement; //code to be executed if condition is false;
}

<?php
$a=10;
$b=20;
if ($a==$b)
{ echo "A is Equal to B"; }
else if($a>=$b)
{ echo "A is Greater than or Equal to B"; }
else
SWITCH STATEMENT

 The switch statement is similar to a series of IF statements on the same expression. In


many occasions, you may want to compare the same variable (or expression) with
many different values, and execute a different piece of code depending on which value
it equals to. This is exactly what the switch statement is for.

SYNTAX

switch ( expression ) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
EXAMPLE
break;
default:
// execute this if no break statement
// has been encountered hitherto
}

EXAMPLE
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
2.6.2 LOOPING STRUCTURE
case 2:
echo "i equals 2";
} ?>
 for
 while
 do...while
 foreach

FOR LOOP

Loops through a block of code a specified number of times.

SYNTAX:

for (initialization; condition; increment)


{
code to be executed;
}

EXAMPLE

<?php

for ($i= 1; $i<= 5; $i++)


{
echo $i ;
}
?>
Output
12345

WHILE LOOP

Loops through a block of code if and as long as a specified condition is true.

SYNTAX:
while (condition)
{
code to be executed;
}

EXAMPLE:

<?php
$i = 1;
while($i < 5)
{

echo $i;
$i++;
} ?>
Output:
12345
DO...WHILE LOOP

Loops through a block of code once, and then repeats the loop as long as a special
condition is true.

SYNTAX:

do
{
code to be executed;
}
while (condition);

EXAMPLE:

<?php
$i = 1;
do
{
echo $i;
$i++;
}
while( $i < 5 );
?>
Output:
12345

FOREACH LOOP

 The foreach statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one and in
the next pass next element will be processed.

SYNTAX

foreach (array as value)


{
code to be executed;
}

EXAMPLE
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
2.7 ARRAY

 An array is a special variable, which can store multiple values of same datatype in
one single variable.
 For example if you want to store 99 numbers then instead of defining 100 variables
it’s easy to define an array of 99 lengths.

TYPES OF ARRAY:

 Numeric array(Indexed Array)


 Associative array
 Multidimensional array

NUMERIC ARRAY (INDEXED ARRAY)

 A numeric array stores each array element with a numeric index.


 Numeric arrays are similar to tables with a single column. An indexed array can contain
zero or more elements.
 In Numeric arrays, the keys are numeric and starts with 0, and the values can be any
data type.

THERE ARE TWO METHODS TO CREATE A NUMERIC ARRAY.


 In this following example index are automatically assigned (the index starts at 0).

SYNTAX

$friends = array ("Ronak","Vipul","Shakshi");


In this following example we assign the index manually.

$friends[0] = " Ronak";


$friends[1] = " Vipul ";
$friends[2] = " Shakshi ";

EXAMPLE

Reading from arrays is just a matter of pointing to a specific index or key.


<?php
$friends[0]="Ronak";
$friends[1]="Vipul";
$friends[2]="Shakshi";
echo $friends[0] . " and " . $friends[1] . " are Brothers.";
?>
Output:
Ronak and Vipul are Brothers.

ASSOCIATIVE ARRAY

 An associative array, each ID key is associated with a value.


 When storing data about specific named values, a numerical array is not always the best
way to do it.
 With associative arrays we can use the values as keys and assign values to them.
 To store the marks of students in an array, a numerically indexed array would not be the
best choice. Instead, we could use the students names as the keys in our associative
array, and the value would be their respective marks.

SYNTAX

$student_marks = array("Ronak"=>80, "Vipul"=>90, "Shakshi"=>85);

This is equivalent to the following:


$student_marks["Ronak"] = 80;
$student_marks["Vipul"] = 90;
$student_marks["Shakshi"] = 85;

EXAMPLE
<?php

$student_marks["Ronak"] = 80;
$student_marks["Vipul"] = 90;
$student_marks["Shakshi"] = 85;

Example:1
foreach ($student_marks as $name=>$marks)
{
echo "Studnet name is ".$name ." have got ".$marks." Marks<br>";
}

?>
Output of Example1:
Studnet name is Ronak have got 80 Marks
Studnet name is Vipul have got 90 Marks
Studnet name is Shakshi have got 85 Marks

Example2:
foreach ($student_marks as $name)
{
echo "Studnet Marks is ".$name."<br>";
}
Output:
Studnet Marks is 80
Studnet Marks is 90
Studnet Marks is 85

MULTIDIMENSIONAL ARRAY:

 In multi-dimensional array each element in the main array can also be an array.
 Each element in the sub-array can be an array, and so on.
 Values in the multi-dimensional array are accessed using multiple indexes.

SYNTAX

$var_name=array(keys1=>array(childkey1=>value1,childkey2=>value2….));

EXAMPLE:

<?php
$marks = array(
"Amar" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
<?php
$family = array("Mike"=>array("Ben","Katty","Paul"));
$family = array("Mike"=>array("Ben","klatty","Paul"),"Johnson"=>array("Shena","Glenn"));
echo "The family Johnson have two members;". $family['Johnson'][0] . "and " .
$family['Johnson'][1] ;
?>

PHP AND HTML FORMS / PROCESSING FORM INPUT

GET METHOD
 The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the? Character.

http://localhost/index.php?name1=value1&name2=value2

 The GET method is restricted to send upto 1024 characters.


 Never use GET method if you have password or other sensitive information to be sent to
the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.
 The PHP provides $_GET associative array to access all the sent information using GET
method.

<?php
if(isset($_GET["submit"]))
{
echo $_GET['name'];
echo $_GET['city'];

}
?>
<html>
<body>
<form method="GET">
Name: <input type="text" name="name" />
City: <input type="text" name="city" />
<input type="submit" name="submit" /> </form></body></html>

POST METHOD
 The POST method transfers information via HTTP headers. The information is encoded
as described in case of GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
 The PHP provides $_POST associative array to access all the sent information using GET
method.

EXAMPLE:
<?php
if(isset($_POST["submit"]))
{
echo $_POST['name'];
echo $_POST['city'];

}
?>
<html>
<body>
<form method="POST">
Name: <input type="text" name="name" />
City: <input type="text" name="city" />
<input type="submit" name="submit" />
</form>
</body>
</html>

HOW HTML FORMS WORK

o A web form has two parts: the HTML ‘front end’ and a back end form processor. The HTML
front end part handles the presentation while the back end handles the form submissions (like
saving the form submissions, sending emails etc).
o The back end form processor script is usually written in languages like PHP, ASP or Perl.
o The image below illustrates the concept:
1. A visitor visits a web page that contains a form.
2. The web browser displays the HTML form.
3. The visitor fills in the form and submits
4. The browser sends the submitted form data to the web server
5. A form processor script running on the web server processes the form data
6. A response page is sent back to the browser.

2.9 STRING MANIPULATION

2.9.1 FORMATTING STRINGS

Concatenation

Concatenation is a programming word for adding strings together. In PHP, the concatenation
operator is a dot (.). Generally, concatenation is used to combine literal text with variables or
values returned from functions. The example below illustrates this.
Code Sample:

<body>
<h1>Concatenation</h1>
<?php
$firstName = 'Paul';
$greeting = 'Hello';
echo $greeting . ' ' . $firstName . '!';
?>
<h2>Using Double Quotes to Avoid the Concatenation Operator</h2>
<?php
echo "$greeting $firstName!";
?>
<h2>Double quotes don't work when concatenating
the results of a function call</h2>
<?php
echo $greeting . ' ' . $firstName . '! Today is ' . date('l') . '.';
?>
</body>

2.9.2 STRING MANIPULATION FUNCTIONS

 chr()
 The chr() function returns a character from the specified ASCII value.
SYNTAX:
chr(ascii)

PARAMETER:

Parameter Description

Ascii Required. An ASCII value


EXAMPLE:

 ord()
 The ord() function returns the ASCII value of the first character of a string.
SYNTAX:

PARAMETER:

EXAMPLE:

 strtolower()
 This function converts the string to lower case.
SYNTAX:

PARAMETER:

Parameter Description
string Required. Specifies the string to convert

EXAMPLE:
<?php
echo strtolower("Hello BCA 3 Sem");
?>
Output:
hello bca 3 sem

 strtoupper()
 This function converts the string to upper case.
SYNTAX:
strtoupper(<string>);

PARAMETER:

Parameter Description

string Required. Specifies the string to convert

EXAMPLE:
<?php
echo strtoupper("Hello BCA 3 Sem");
?>
Output:
HELLO BCA 3 SEM

 strlen()
 This function returns the length of the string.
SYNTAX:
strlen(<string>);

PARAMETER:

Parameter Description

string Required. Specifies the string to check


EXAMPLE:
<?php
echo strlen("Hello");
?>
OUTPUT
5

 ltrim()
 The ltrim() function is used to remove white spaces or other predefined characters
form the left side of the string.
SYNTAX:
ltrim(string_name, char_list)

PARAMETER:
Parameter Description
String Required. Specifies the string to check

Charlist Optional. Specifies which characters to remove from the


string. If omitted, all of the following characters are removed:

 "\0" - NULL
 "\t" - tab
 "\n" - new line
 "\x0B" - vertical tab
 "\r" - carriage return
 " " - ordinary white space

EXAMPLE
<?php
$text1=" Hello BCA 3 Sem";
$text2="\t\n Hello BCA 3 Sem";
echo ltrim($text1)."<br>";
echo ltrim($text2);
?>
OUTPUT:
Hello BCA 3 Sem
Hello BCA 3 Sem

 rtrim()
 The rtrim() function is used to remove the whitespaces and other predefined
characters from the right side of a string.
SYNTAX:

rtrim(string_name, char_list)
 PARAMETER:

Parameter Description
string Required. Specifies the string to check

charlist Optional. Specifies which characters to remove from the string. If


omitted, all of the following characters are removed:
"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space

EXAMPLE:
<?php
$text1="Hello BCA 3 Sem ";
$text2="\t\n Hello BCA 3 Sem";
echo rtrim($text1)."<br>";
echo rtrim($text2,'em');
?>
Output:
Hello BCA 3 Sem
Hello BCA 3 S

 trim()
 The trim() function is used to remove the white spaces and other predefined
characters from the left and right sides of a string.
SYNTAX:
trim(string_name, char_list)

PARAMETER:

Parameter Description

string Required. Specifies the string to check

char_list Optional. Specifies which characters to remove


from the string. If omitted, all of the following
characters are removed:

 "\0" - NULL
 "\t" - tab
 "\n" - new line
 "\x0B" - vertical tab
 "\r" - carriage return
 " " - ordinary white space

EXAMPLE:

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
OUTPUT
Hello World!
llo Worl

 substr ()
 The substr() function used to cut a part of a string from a string, starting at a specified
position.
SYNTAX:
substr(string_name, start_pos, length_to_cut)
PARAMETER:

Parameter Description

string_name Required. The input string.

start_pos Required.

Refers to the position of the string to start cutting.


A positive number : Start at the specified position in the string.
A negative number : Start at a specified position from the end of
the string.
length_to_cut Optional.

Length of the string to cut from the main string.


A positive number: Start at the specified position in the string.
A negative number: Start at a specified position from the end of
the string.

EXAMPLE:

<?php
$str="Welcome to BCA 3 Sem";
echo substr($str,0,5)."<br>";
echo substr($str,5);
?>
Welco
me to BCA 3 Sem

 strcmp ()
 The strcmp() function is used to compare two strings.
SYNTAX:
strcmp(string1, string2)

PARAMETER:

Parameter Description

string1 Required. The first string

string2 Required. The second string


EXAMPLE:
<?php
$str="Welcome to BCA 3 Sem";
$str1="Welcome to BCA 3 Sem";
echo $result=strcmp($str,$str1)."<br>";
$str2="Welcome to BCA 3";
$str3="Welcome to BCA 3 Sem";
echo $result=strcmp($str2,$str3)."<br>";
echo $result=strcmp($str3,$str2)."<br>";
?>
Output
0 -4 4

 strcasecmp ()
 The strcasecmp() function is used to compare two case sensitive strings.
SYNTAX:
strcasecmp(string1, string2)

PARAMETER:

Parameter Description

string1 Required. The first string

string2 Required. The second string

EXAMPLE:
<?php
$str="Atmiya";
$str1="ATMIYA";
echo $result=strcasecmp($str,$str1)."<br>";
$str2="ATMIYA";
$str3="ATMIYA RJT";
echo $result=strcmp($str2,$str3)."<br>";
echo $result=strcmp($str3,$str2)."<br>";
?>
Output
0 -4 4
 strpos()
 The strpos() function returns the position of the first occurrence of a string inside
another string.
SYNTAX:

strpos(string,find,start)

PARAMETER:

Parameter Description

string Required. Specifies the string to search

Find Required. Specifies the string to find

Start Optional. Specifies where to begin the search

EXAMPLE:

<?php
$str="Aatmiya";
$str1="ATMIYA";
echo strpos($str,"a",3)."<br>";
echo strpos($str1,"b");
?>
Output
6

 strrpos ()
 The strrpos() function finds the position of the last occurrence of a string inside
another string.
SYNTAX:
strrpos(string,find,start)

PARAMETER:

Parameter Description

string Required. Specifies the string to search


Find Required. Specifies the string to find

Start Optional. Specifies where to begin the search

EXAMPLE:

<?php
$str="Aatmiy";
$str1="ATMIYATA";
echo strrpos($str,"at")."<br>";
echo strrpos($str1,"A",6);
?>
Output
\
1
7

 strstr ()
 The strstr() function searches for the first occurrence of a string inside another string.
 This function returns the rest of the string (from the matching point).
 This function is case sensitive.
SYNTAX:
strstr(string,search,before_search)

PARAMETER :

Parameter Description

string Required. Specifies the string to search

search Required. Specifies the string to search for. If this


parameter is a number, it will search for the
character matching the ASCII value of the number

before_search Optional. A boolean value whose default is "false". If


set to "true", it returns the part of the string before
the first occurrence of the search parameter.

EXAMPLE:
<?php
$str="Aatmiy";
echo strstr($str,"at“);
?>
atmiy
 stristr ()
 The stristr() function searches for the first occurrence of a string inside another string.
SYNTAX:
stristr(string,search)

PARAMETER:

Parameter Description

string Required. Specifies the string to search

search Required. Specifies the string to search for. If this


parameter is a number, it will search for the
character matching the ASCII value of the number

before_search Optional. A boolean value whose default is "false". If


set to "true", it returns the part of the string before
the first occurrence of the search parameter.

EXAMPLE:
<?php
$str="Aatmiy";
echo stristr($str,"At")."<br>";
?>
Output
atmiy

 str_replace ()
 The str_replace() function replaces some characters with some other characters in a
string.
SYNTAX:
str_replace(find,replace,string,count)

PARAMETER:
Parameter Description

find Required. Specifies the value to find

replace Required. Specifies the value to replace the value in find

string Required. Specifies the string to be searched

count Optional. A variable that counts the number of replacements

EXAMPLE:
<?php
$str="Atmiya College";
echo str_replace("College","Rajkot",$str)."<br>";
?>
OUTPUT
Atmiya Rajkot

 strrev ()
 The strrev() function is used to reverse a string.
SYNTAX:
strrev(main_string)

PARAMETER:

Parameter Description

main_string Required. The string to be reversed.

EXAMPLE:

<?php
$str="Atmiya College";
echo strrev($str);
?>
OUTPUT
egelloC ayimtA
 echo ()
 The echo () function is used to output the given argument. It can output all types of
data and multiple outputs can be made with only one echo () command.
SYNTAX:
echo (arg1, arg2... )

PARAMETER:

Parameter Description
arg1 Required. Specifies the string to display.

Arg2 Optional

EXAMPLE:
<?php
$abc='We are learning PHP';
$xyz='vsc-project.blogspot.com';
echo "$abc at $xyz <br />";
echo $abc;
echo "<br />"; // creating a new line
echo $xyz;
echo "<br />"; // creating a new line
// Displaying arrays
$fruits=array('fruit1'=>'Apple','fruit2'=>'Banana');

echo "Fruits are : {$fruits['fruit1']} and


{$fruits['fruit2']}" ;
?>
Output
We are learning PHP at vsc-project.blogspot.com
We are learning PHP
vsc-project.blogspot.com
Fruits are : Apple and Banana

 print ()
 The print () function is used to output the given argument. It can output all types of
data and multiple outputs can be made with only one print () command.
 Print() is not actually a real function, it is a language construct like echo. There are
some difference between the two, echo is marginally faster compare to print as echo
does not return any value. Echo can accept multiple parameters without parentheses
but print can accept only one parameter.

SYNTAX:
print(string $val)

PARAMETER:

Parameter Description
$val Required. The input data.

EXAMPLE:
<?php
print 'One line simple string.<br />';
print 'Two line simple
string example<br />';
print 'Tomorrow I \'ll learn PHP global variables.<br />';
print 'This is a bad command : del c:\\*.* <br />'; ?>
Output
One line simple string.
Two line simple string example
Tomorrow I 'll learn PHP global variables.
This is a bad command : del c:\*.*

 explode ()
 The explode() function breaks a string into an array.
SYNTAX:
explode(separator,string,limit)

PARAMETER:

Parameter Description
Separator Required. Specifies where to break the string

String Required. The string to split

Limit Optional. Specifies the number of array elements to return.


Possible values:
Greater than 0 - Returns an array with a maximum of limit element(s)
Less than 0 - Returns an array except for the last -limit elements()
0 - Returns an array with one element

EXAMPLE:
<?php $str = 'one,two,three,four';
// zero limit
echo "<br>";
print_r(explode(',',$str,0));
// positive limit
echo "<br>";
print_r(explode(',',$str,2));
echo "<br>";
// negative limit
print_r(explode(',',$str,-1)); ?>
Output
Array ( [0] => one,two,three,four )
Array ( [0] => one [1] => two,three,four )
Array ( [0] => one [1] => two [2] => three )

 implode ()
 The implode() function is used to join array elements with a string.
SYNTAX:
implode (string_join, array_name)

PARAMETER:

Parameter Description
string_join Optional.String-join works as a connector between the array
elements. Default value is a empty string (" ").

array_name Required. The array who's elements will be joined.

EXAMPLE:
<?php
$array_name=array('First Name', 'Middle Name', 'Last Name');
$join_string=implode("-", $array_name);
echo $join_string;
echo '<br>';
$join_string=implode(" ", $array_name);
echo $join_string;
?>
Output
First Name-Middle Name-Last Name
First Name Middle Name Last Name
 join ()
 The join() function is used to join array elements with a string. The join() function is
similar to implode() function.
SYNTAX:
join (string_join, array_name)

PARAMETER:

Parameter Description

string_join Optional. String-join is work as a connector between the


array elements. Default value is a empty string (" ").

array_name Required. The array who's elements will be joined.

EXAMPLE:
<?php
$array_name=array('1','2','3','4','....');
$join_string=join(",", $array_name);
echo $join_string;
echo '<br>';
$array_name=array('A','B','C','D','E');
$join_string=join("-", $array_name);
echo $join_string; ?>
Output
1,2,3,4,.... A-B-C-D-E

 md5 ()
 The md5() function is used to calculate the md5 hash (the hash as a 32-character
hexadecimal number ) of a string.
SYNTAX:
md5(input_string, raw_output)
PARAMETER:

Parameter Description
input_string Required.The input string.

raw_output Optional.Refers hex or binary output format, Returns raw 16 bit


binary format if raw_output sets TRUE and return 32 bit hex
format for setting FALSE (default).

EXAMPLE:
<?php
$input_string = 'Good Morning';
echo 'Original string : '.$input_string.'<br>';
echo '16 bit binary format : '.md5($input_string, TRUE).'<br>';
echo '32 bit binary format : '.md5($input_string).'<br>'; ?>
Output
Original string : Good Morning
16 bit binary format : r y†” du?Û£¿ân
32 bit binary format : 72a079088694099d64753fdba3bfe26e

 md5 ()
 The md5() function is used to calculate the md5 hash (the hash as a 32-character
hexadecimal number ) of a string.
SYNTAX:
md5(input_string, raw_output)

PARAMETER:

Parameter Description
input_string Required.The input string.

raw_output Optional.Refers hex or binary output format, Returns raw 16 bit


binary format if raw_output sets TRUE and return 32 bit hex
format for setting FALSE (default).

EXAMPLE:
<?php
$input_string = 'Good Morning';
echo 'Original string : '.$input_string.'<br>';
echo '16 bit binary format : '.md5($input_string, TRUE).'<br>';
echo '32 bit binary format : '.md5($input_string).'<br>';
?>
Output
Original string : Good Morning
16 bit binary format : r y†” du?Û£¿ân
32 bit binary format : 72a079088694099d64753fdba3bfe26e
 str_split ()
 The str_split() function is used to convert a string to an array.
SYNTAX:
str_split(string_name, split_length)

PARAMETER:

Parameter Description
string_name Required. The string to be split.

split_length Optional. The length of the chunk.

EXAMPLE:
<?php
$string_name='vsc-project.blogstop.com';
print_r(str_split($string_name));
echo '<br>';
print_r(str_split($string_name,4));
echo '<br>'; ?>
Output
Array ( [0] => v [1] => s [2] => c [3] => - [4] => p [5] => r [6] => o [7] => j [8] => e [9] => c
[10] => t [11] => . [12] => b [13] => l [14] => o [15] => g [16] => s [17] => t [18] => o [19]
=> p [20] => . [21] => c [22] => o [23] => m )
 str_shuffle
Array ( [0]()
=> vsc- [1] => proj [2] => ect. [3] => blog [4] => stop [5] => .com )
 The str_shuffle() function randomly shuffles a string.
SYNTAX:
str_shuffle(string_name)

PARAMETER:

Parameter Description
string_name Required. The input string.

EXAMPLE:
<?php
$string_name='vsc-project.blogspot.com';
$shuffled_string=str_shuffle($string_name);
echo $shuffled_string;
?>
Output
b-..roosclcopvoetsctgmpj

 strcspn ()
 The strcspn() function is used to get the number of characters that occur between the
start of the main string and the first occurrence of any character listed in the second
string.
SYNTAX:
strcspn(main_string, second_string, start_position, string_length)

PARAMETER:

Parameter Description
main_string Required. The initial string.

second_string Required .The second string whose characters will be checked.

start_position Optional.Starting position of the string to examine.

string_length Optional.Length of the string to examine.

EXAMPLE:
<?php
echo strcspn('vsc-project.blogspotcom', '.');
?>
Output
11

 strpbrk ()
 The strpbrk() function searches a string for any of the specified characters. This
function is case-sensitive.
SYNTAX:
strpbrk(string,charlist)
PARAMETER:

Parameter Description
string Required. Specifies the string to search

charlist Required. Specifies the characters to find

EXAMPLE:
<?php
echo strpbrk("Hello world!","W");
echo "<br>";
echo strpbrk("Hello world!","w");
?>
Output
world!

 substr_compare ()
 The substr_compare() function is used to compare two strings from a given starting
position in the main string.
SYNTAX:
substr_compare(main_string, compare_string, star_pos, length, case_insensitivity)

PARAMETER:

Parameter Description
string Required. Specifies the string to search

charlist Required. Specifies the characters to find

EXAMPLE:
<?php
echo strpbrk("Hello world!","W");
echo "<br>";
echo strpbrk("Hello world!","w");
?>
Output
world!
 substr_count ()
 The substr_count() function is used to count the number of times a substring occurs in
a string. Note that substring is case sensitive.
SYNTAX:
substr_count(string1, string2, nstart, nlength)

PARAMETER:

Parameter Description
string1 Required. The string to search in.

string2 Required. The substring to search for.

nstart Optional .The position where string to start searching.

nlength The length of the string to be searched for.

EXAMPLE:
<?php
$string1="Welcome to Pradip Vanparia";
echo substr_count($string1,'co')."<br>";
echo substr_count($string1,'ra',4)."<br>";
echo substr_count($string1,'co',4,4)."<br>";
?>
Output
1
1
0

 ucfirst ()
 The ucfirst() function is used to convert the first character of a string to uppercase.
SYNTAX:
ucfirst(string_name)

PARAMETER:

Parameter Description
string_name Required. The input string.
EXAMPLE:

 ucwords ()
 The ucwords() function is used to convert the first character of each word in a string
to uppercase.
SYNTAX:

PARAMETER:

Parameter Description
string_name Required. The input string.

EXAMPLE:
<?php
$string_name='pradip vanparia';
$string_name=ucwords($string_name);
echo $string_name;
?>
Output
Pradip Vanparia

2.9.3 MAGIC QUOTES


 Magic quotes is a controversial feature of the PHP scripting language, wherein strings
are automatically escaped—special characters are prefixed with a backslash—before
being passed on. It was introduced to help newcomers write functioning SQL
commands without requiring manual escaping.
 It was later described and widely misinterpreted as intended to prevent inexperienced
developers from writing code that was vulnerable to SQL injection attacks.
 Magic Quotes, generally speaking, is the process of escaping special characters with a
'\' to allow a string to be entered into a database. This is considered 'magic' because
PHP can do this automatically for you if you have magic_quotes_gpc turned on.
 More specifically if magic_quotes_gpc is turned on for the copy of PHP you are using
all Get, Post & Cookie variables in PHP will already have special characters like ", '
and \ escaped so it is safe to put them directly into an SQL query.
 To enable magic_quotes_gpc find this function in php.ini file , by default the value of
magic_quotes_gpc = Off.
 Now set magic_quotes_gpc = On back to magic_quotes_gpc = Off in your php.ini file.

ADVANTAGES
o You can forget to put an addslashes() call around submitted variables and not
have your SQL query fail.
o You can skip adding slashes manually altogether to keep your code less cluttered.

DISADVANTAGES
o Any code using SQL written for PHP 3.x.x has to be examined to remove
addSlashes calls.
o Cases where form submissions are sent back to the browser must have the slashes
removed manually with a call to stripslashes().
o If magic quotes are ever turned off for this server, or the code is moved to a server
where magic quotes isn't enabled your scripts will fail. Or worse, not fail
immediately and only exhibit strange behaviour.
o Any string operations on submitted variables, even simple 'if' statements must
take into account the possiblity of slashes warping in the content.
o Magic quotes breeds developer sloppiness. Escaping variables inserted into an
SQL query (in my opinion) is something that a developer should know and think
about. Not just assume everything is dandy.
EXAMPLE

<?php
echo "Altered Text: ".$_POST['question'];
?>
<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>
</form>
OUTPUT
Altered Text: Sandy said, \"It\'s a beautiful day outside and I like to use \\\'s.\"
o This simple form will display to you what magic quotes is doing. If you were to enter and
submit the string: Sandy said, "It's a beautiful day outside and I like to use \'s." You
would receive the following output.
o Magic quotes did a number on that string, didn't it? Notice that there is a backslash before
all of those risky characters we talked about earlier. After magic quotes:
o A backslash \ becomes \\
o A quote ' becomes \'
o A double-quote " becomes \"

o Now say that you wanted to remove the escaping that magic quotes puts in, you have two
options: disable magic quotes or strip the backslashes magic quotes adds.

REMOVING BACKSLASHES - STRIPSLASHES()


Before you use PHP's backslash removal function stripslashes it's smart to add
some magic quote checking like our "Are They Enabled?" section above. This
way you won't accidentally be removing slashes that are legitimate in the future if
your PHP's magic quotes setting changes in the future.
EXAMPLE

<?php
echo "Removed Slashes: ";
// Remove those slashes
if(get_magic_quotes_gpc())
echo stripslashes($_POST['question']);
else
echo $_POST['question'];

?>

<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>
</form>
2.10 REUSING CODE AND WRITING FUNCTIONS

Writing reusable code results in

- time and money savings,


- more consistent and bug free code,
- and the ability to hide complex code from less seasoned developers.

Including Files

 PHP provides two common constructs for including files in web pages: require and
include. They are basically the same with one minor difference. require throws a fatal
error when it fails; whereas, include only gives a warning. If you need the included file
to continue to process the page, you should use require.
 It is important to keep in mind that a PHP tag cannot start in a calling file and continue
in an included file. All PHP code in the included file must be nested in PHP tags.
 Using require() or include() enables you to load a file into your PHP file.
 One more thing to mention here is that there are two variations to require()
and include(): require_once() and include_once() and you might have guessed what
they mean? They mean that the respective files can only be included or required once!
Consider a situation where you have included a file twice without knowing, you will
get an error. So, if you are cautious, you might want to try require() or include()
because they are faster to execute.

Consider a file named: reusablefile.php

<?php
echo 'Hello there, this is a reusable code <br />';
?>
And now consider another file named: main.php

<?php
echo 'This is the main file for testing stuff <br />';
require('reusablefile.php');
echo 'This is where the script ends at this moment <br />';
?>

Now the outcome: Running the main.php file will return the page shown:

PHP require_once()
require_once() statement can be used to include a php file in another one, when you may need to
include the called file more than once. If it is found that the file has already been included,
calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with require_once() statement, and does not find b.php,
a.php stops executes causing a fatal error.
Syntax:
Require_once(‘name of the calling file with path’);
Example
<?php
echo "today is:".date("Y-m-d");
?>

The above file is x.php


The above file x.php, is included twice with require_once() statement in the following file y.php.
But from the output you will get that the second instance of inclusion is ignored, since
require_once() statement ignores all the similar inclusions after the first one.

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

View this example in the browser


If a calling script does not find a called script with require_once statement, it halts the execution
of the calling script.

PHP Include_once()

The include_once() statement can be used to include a php file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with include_once() statement, and does not find b.php,
a.php executes with a warning, excluding the part of the code written within b.php.

Syntax:
Include_once(‘name of the called file with path’);
Example:
<?php
echo "today is:".date("Y-m-d");
?>

The above file is x.php


The above file x.php, is included twice with include_once() statement in the following file y.php.
But from the output you will get that the second instance of inclusion is ignored, since
include_once() statement ignores all the the similar inclusions after the first one.

<?php
include_once('x.php');
include_once('x.php');
?>

View the example in the browser


If a calling script does not find a called script with include_once statement, it halts the execution
of the calling script.

auto_prepend_file and auto_append_file


The PHP auto_prepend_file and auto_append_file directives can only be used in php.ini files. They do
NOT work when used in .htaccess file.

The purpose of these PHP configuration directives is to execute a specified file before or after any PHP
script stored on your computer/server.

This is similar to using a require() function at the beginning or end of a PHP script. The
auto_prepend_file directive parses a file before executing any PHP file, so this can be extremely useful if
you have a set of user defined PHP functions which need to be called in all PHP scripts.

Below example explains the scenario, first lets created two functions for addition and
subtraction.

<?php

function add($a,$b)

return ($a+$b);

function subtract($a,$b)

return($a-$b);
}

?>

Save the code in a separate file myfunctions.php. Now edit the php.ini file, this file is located
in /etc/php.ini in Linux, C:\PHP\php.ini in Windows, C:\wamp\bin\php\php.ini in WAMP and
C:\xampp\php\php.ini in XAMPP. Find and edit the following line

auto_prepend_file = "Location to myfunction.php"

If you’re editing a custom php.ini file you should manually add this line. The location you
specify should be an absolute location like /var/www/html/myfunction.php windows users
should use forward slash in their file path C:/wamp/www/myfunction.php

Now all you need to do is to call this function in any PHP script you code. The usage of
auto_append_file directive is also similar; the only difference is the file specified is parsed
AFTER a PHP script executes.

The way in which these configuration directives work might make you think you can use these
for adding a header and footer all pages, if you plan to do so remember that while execution the
files are merely prepended and appended to the PHP file requested hence you should code in
such a way that the header file has the just opening tag for <html>, entire contents of the <head>
tag, the opening tag for <body> then the header content. Then the footer file will contain the
footer content, closing </body> tag and closing </html> tag in that order.

So the main file you code should only have the content that comes after the header contents and
before the footer contents.

So it is best you use the auto_prepend_file and auto_append_file directives for including scripts
that don’t generate an output viewable on the browser like visitor tracking scripts, user
definitions of functions.
2.11 USER FUNCTIONS

Besides the built-in PHP functions, we can create our own functions.

 A user function is a block of statements that can be used repeatedly in a program.


 User functions are used to make common tasks easier and to make code more modular
and easier to read.
 A function will not execute immediately when a page loads.
 A function will be executed by a call to the function.

Syntax

function function-name()

statement 1 :

statement 2 :

statement 3 :

......

2.11.1 Defining and Calling Functions

A simple function is defined as follows.

Syntax

function myfunct()

{
do this;

do that;

do this other thing;

Example

<?php
function myfunction()
{
echo “Good Morning”;
}
myfunction();
?>

2.11.2 PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just seperate them with a comma.

There are three different ways of passing arguments to a function, arguments by value (the
default), passing by reference, and default argument values.

Passing arguments by value

Example

function addNums($param1, $param2, $param3)


{
$sum = $param1 + $param2 + $param3;
echo 'The sum is ' . $sum;
}
addNums(20,50,30);
Returning Values

In PHP values are returned by return statement. The return values must be specified in the
variable. If the statement is called within a function the function is terminated
immediately and passes control back to previous position from which it was called.

The return statement can return any type of data.

Example

function addNums($param1, $param2, $param3)


{
$sum = $param1 + $param2 + $param3;
return $sum;
}
result=addNums(20,50,30);
echo $result;

Passing arguments by reference

By default the function arguments are passed by value. If you want to allow a function to
change its arguments, you must pass the arguments by reference. To pass an argument to
a function as reference, simply add an ampersand (&) character before the variable name.

<?php

function cube(&$x)

$x=$x*$x*$x;

result=5;
cube($result);

echo $result;

?>

Output

125

2.11.3 PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:

Example

<?php
function setHeight($minheight = 50)

{
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

Output:

The height is: 350


The height is: 50
The height is: 135
The height is: 80
2.11.4 VARIABLE SCOPE

In PHP, variables declared outside of functions are not available by default inside of functions.
The following code illustrates this:

Example

<html>
<head>
<title>Local Variables</title>
</head>

<body>
<?php

$a = 10;
$b = 5;

function incrNumBy()
{
$a += $b;
}
incrNumBy(); //results in two warnings as $a and $b are
//undefined in the function scope
echo $a; //outputs 10 to the browser
?>
</body>
</html>

To make the variables available to the function, they must be declared within the function as
global variables using the global keyword.

Example

<html>
<head>
<title>Global Variables</title>
</head>

<body>
<?php
$a = 10;
$b = 5;
function incrNumBy()
{
global $a,$b;
$a += $b;
}
incrNumBy();
echo $a; //outputs 15 to the browser
?>
</body>
</html>

2.11.5 BY REFERENCE V/S BY VALUE

By default, variables are passed to functions by value, meaning that the function's receiving
variables get copies of the values received rather than pointers to them. If the receiving variables
are modified, the passed variables remain unaffected. The following code illustrates this.

Example

<html>
<head>
<title>By Value</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy($num,$incr)
{
$num += $incr;
}

incrNumBy($a,$b);
echo $a; //outputs 10 to the browser
?>
</body>
</html>

The above code outputs "10" to the browser. Although $num was incremented by 5, $a was
unaffected by the function call. To pass a variable by reference, put an ampersand (&) before the
parameter in the function definition.
Example

<html>
<head>
<title>By Reference</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy(&$num,$incr)
{
$num += $incr;
}

incrNumBy($a,$b);
echo $a; //outputs 15 to the browser
?>
</body>
</html>

This time the function outputs "15" because $num references the variable $a itself. So, any
change in $num will affect $a.

2.12 FORM PROCESSING

Processing forms generally involves the following tasks:

1. Writing the HTML code to output the form.


2. Writing validation code to validate the form entries after the form is submitted.
3. Writing code to output errors if there are any.
4. Writing code to process the form entries if they are all valid.

Although these tasks are all separate, some are dependent on others. For example, if errors are
found when the form is submitted, it is nice to re-output the form, but the HTML code may be
different from the original form as you will likely want to include error messages and also echo
the values that the user entered. It's very easy to get your code all tangled up resulting in what is
known as spaghetti code. We will now examine one approach for organizing code using
functions and includes making it easier to maintain.

Code Organization

Application Flow

The application we are building works like this:

1. When the user first visits, she is presented with a form to fill out.
2. If she fills out the form...
o Correctly
 She is presented with another form to confirm her entries.
 After confirming her entries, the data will be processed (e.g, entered into a
database or emailed to someone).
o Incorrectly
 She is presented with the same form with her entries in tact and
appropriate error messages displayed.

Application Files

To make our code easier to maintain, we will organize it as follows:

1. Includes/init.php - Initializes and sets some variables.


2. AddEmployee.php - Contains code that defines the flow of the application.
3. Includes/EmployeeForm.php - Contains code to display entry form.
4. Includes/ProcessEmployee.php - Contains code to process the original form entry. If
there are errors, they will be displayed on the page. If there are no errors, the user's
entries will be displayed with a "Confirm" button.
5. Includes/InsertEmployee.php - Contains code to insert the employee into a database.
(This file is currently empty.)
6. Includes/fnFormPresentation.php - Contains a library of functions for presenting form
fields.
7. Includes/fnFormValidation.php - Contains a library of functions for validating form
entries.
8. Includes/fnStrings.php - Contains a couple of useful string functions.
9. Includes/fnDates.php - Contains a useful date function.
We will examine each of these files.

Example
ReusingCode/Demos/Includes/init.php
<?php
$showForm = true;

$mgrEntries = array();
$mgrEntries[1]='Nancy Davolio';
$mgrEntries[2]='Andrew Fuller';
$mgrEntries[3]='Janet Leverling';
$mgrEntries[4]='Margaret Peacock';
$mgrEntries[5]='Steven Buchanan';
$mgrEntries[6]='Michael Suyama';
$mgrEntries[7]='Robert King';
$mgrEntries[8]='Laura Callahan';
$mgrEntries[9]='Anne Dodsworth';

$errors = array();
$dbEntries = array( 'FirstName'=>',
'LastName'=>',
'Email'=>',
'Title'=>',
'TitleOfCourtesy'=>',
'Address'=>',
'City'=>',
'Region'=>',
'PostalCode'=>',
'Country'=>',
'HomePhone'=>',
'Extension'=>',
'Notes'=>',
'ReportsTo'=>',
'Password'=>',
'Email'=>',
'BirthMonth'=>1,
'BirthDay'=>1,
'BirthYear'=>date('Y'),
'HireMonth'=>1,
'HireDay'=>1,
'HireYear'=>date('Y'));
$browserEntries = array();
?>
This file sets several variables used throughout the application.

Example

ReusingCode/Demos/AddEmployee.php
<?php
require 'Includes/fnFormValidation.php';
require 'Includes/fnFormPresentation.php';
require 'Includes/fnStrings.php';
require 'Includes/fnDates.php';
require 'Includes/init.php';
?>
<html>
<head>
<title>Add Employee</title>
<style type="text/css">
.Error {color:red; font-size:smaller;}
</style>
</head>
<body>
<?php
require 'Includes/Header.php';

if (array_key_exists('Submitted',$_POST))
{
require 'Includes/ProcessEmployee.php';
}
elseif (array_key_exists('Confirmed',$_POST))
{
require 'Includes/InsertEmployee.php';
}

if ($showForm)
{
require 'Includes/EmployeeForm.php';
}

require 'Includes/Footer.php';
?>
</body>
</html>
The code is relatively easy to read. Things to note:

1. At the very top, we include several files we will need for the application.
2. In the body, we include:
o our header and footer files.
o code that checks which, if either, form was submitted and includes the appropriate
file.
o code that checks whether or not to show the main form. The form will be shown
if:
 it has not yet been submitted.
 it has been submitted with errors.

Example

ReusingCode/Demos/Includes/fnDates.php
<?php
/********* DATE FUNCTIONS *********/

/*
Function Name: monthAsString
Arguments: $m
Returns:
month as string
*/
function monthAsString($m)
{
$months = array();
$months[] = 'January';
$months[] = 'February';
$months[] = 'March';
$months[] = 'April';
$months[] = 'May';
$months[] = 'June';
$months[] = 'July';
$months[] = 'August';
$months[] = 'September';
$months[] = 'October';
$months[] = 'November';
$months[] = 'December';

return $months[$m-1];
}
?>
This file includes a simple function for getting the name of a month (e.g, February) given the
month number (e.g, 2).

Example

ReusingCode/Demos/Includes/fnStrings.php
<?php
/********** STRING FUNCTIONS *********/
/*
Function Name: browserString
Arguments: $string
Returns:
trimmed and escaped string for browser output
*/
function browserString($string)
{
return nl2br(trim(htmlentities($string)));
}

/*
Function Name: dbString
Arguments: $string
Returns:
trimmed and escaped string for database entry
*/
function dbString($email)
{
if (get_magic_quotes_gpc())
{
return trim ($email);
}
else
{
return addslashes(trim($email));
}
}

?>

This file includes functions for cleaning up strings for browser and database output.
Example

ReusingCode/Demos/Includes/fnFormPresentation.php
<?php
/********* FORM PRESENTATION FUNCTIONS *********/

/*
Function Name: textEntry
Arguments: $display,$name,$entries,$errors,$size?
Returns:
one table row as string
*/
function textEntry($display,$name,$entries,$errors,$size=15)
{
$returnVal = "
<tr>
<td>$display:</td>
<td>
<input type='text' name='$name' size='$size'
value=\"" . browserString($entries[$name]) . "\">";

if (array_key_exists($name,$errors))
{
$returnVal .= '<span class="Error" style="white-space:nowrap">* ' .
$errors[$name] .
'</span>';
}

$returnVal .= "</td>
</tr>";

return $returnVal;
}

/*
Function Name: pwEntry
Arguments: $pw1,$pw2,$errors,$size?
Returns:
table rows as string
*/
function pwEntry($pw1,$pw2,$errors,$size=10)
{
$returnVal = "
<tr>
<td>Password:</td>
<td>
<input type='password' name='$pw1' size='$size'>
</td>
</tr>
<tr>
<td>Repeat Password:</td>
<td>
<input type='password' name='$pw2' size='$size'>
</td>
</tr>";

if (array_key_exists('Password',$errors))
{
$returnVal .= addErrorRow('Password',$errors);
}
return $returnVal;
}

/*
Function Name: textAreaEntry
Arguments: $display,$name,$entries,$errors,$cols?,$rows?
Returns:
table rows as string
*/
function textAreaEntry($display,$name,$entries,$errors,$cols=45,$rows=5)
{
$returnVal = "
<tr>
<td colspan='2'>$display:</td>
</tr>
<tr>
<td colspan='2'>
<textarea name='$name' cols='$cols' rows='$rows'>";
$returnVal .= $entries[$name];
$returnVal .= "</textarea>
</td>
</tr>";

if (array_key_exists($name,$errors))
{
$returnVal .= addErrorRow($name,$errors);
}
return $returnVal;
}

/*
Function Name: radioEntry
Arguments: $display,$name,$entries,$errors,$values
Returns:
table rows as string
*/
function radioEntry($display,$name,$entries,$errors,$values)
{
$returnVal = "
<tr>
<td>$display:</td>
<td>$name</td>
</tr>";

return $returnVal;
}

/*
Function Name: selectEntry
Arguments: $display,$name,$entries,$errors,$selected?
Returns:
table rows as string
*/
function selectEntry($display,$name,$options,$errors,$selected=0)
{
$returnVal = "<tr>
<td>$display:</td>
<td>
<select name='$name'>
<option value='0'>Choose one...</option>";
$returnVal .= "</select>
</td>
</tr>";
return $returnVal;
}

/*
Function Name: selectDateEntry
Arguments: $display,$namePre,$month,$day,$year
Returns:
table rows as string
*/
function selectDateEntry($display,$namePre,$month,$day,$year,$errors)
{
$returnVal = "<tr>
<td>$display:</td>
<td>
<select name='$namePre" . "Month'>";
for ($i=1; $i<=12; $i++)
{
if ($i == $month)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>";
}
$returnVal .= monthAsString($i) . '</option>';
}
$returnVal .= "</select>
<select name='$namePre" . "Day'>";
for ($i=1; $i<=31; $i++)
{
if ($i == $day)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>";
}
$returnVal .= "$i</option>";
}
$returnVal .= "</select>
<select name='$namePre" . "Year'>";
for ($i=date('Y'); $i>=1900; $i=$i-1)
{
if ($i == $year)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>$i</option>";
}
$returnVal .= "$i</option>";
}
$returnVal .= '</select>
</td>
</tr>';

if (array_key_exists($namePre . 'Date',$errors))
{
$returnVal .= addErrorRow($namePre . 'Date',$errors);
}
return $returnVal;
}

/*
Function Name: addErrorRow
Arguments: $name
Returns:
table row as string
*/
function addErrorRow($name,$errors)
{
$errorRow = '<tr><td colspan="2" class="Error">* ' .
$errors[$name] .
'</td></tr>';
return $errorRow;
}
?>

This file contains functions for presenting form entries. Several of these functions are complete,
but there are a couple that need to be finished. This will be part of the next exercise.

Example

ReusingCode/Demos/Includes/fnFormValidation.php
<?php
/********* FORM VALIDATION FUNCTIONS *********/

/*
Function Name: checkLength
Arguments: $text,$min?,$max?,$trim?
Returns:
false if $text has fewer than $min characters
false if $text has more than $max characters
true otherwise
*/
function checkLength($text,$min=1,$max=10000,$trim=true)
{
if ($trim)
{
$text = trim($text);
}
if (strlen($text) < $min || strlen($text) > $max)
{
return false;
}
return true;
}

/*
Function Name: checkEmail
Arguments: $email
Returns:
false if $email has fewer than 6 characters
false if $email does not contain @ symbol
false if $email does not contain a period (.)
false if the last @ symbol comes after the last period (.)
true otherwise
*/
function checkEmail($email)
{
return true;
}

/*
Function Name: checkPassword
Arguments: $pw1,$pw2
Returns:
false if $pw1 has fewer than 6 characters
false if $pw1 has more than 12 characters
false if $pw1 and $pw2 do not match
true otherwise
*/
function checkPassword($pw1,$pw2)
{
return true;
}
?>

This file contains functions for validating form entries. One of these functions is complete, but
there are a couple that needs to be finished. This will also be part of the next exercise.

Example
ReusingCode/Demos/Includes/EmployeeForm.php
<h1 align="center">Add Employee</h1>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Submitted" value="true">
<table align="center" border="1" width="500">
<?php
echo textEntry('First name','FirstName',$dbEntries,$errors,15);
echo textEntry('Last name','LastName',$dbEntries,$errors,15);
echo textEntry('Email','Email',$dbEntries,$errors,25);
echo textEntry('Title','Title',$dbEntries,$errors,30);
echo radioEntry('Title of Courtesy','TitleOfCourtesy',
$dbEntries,$errors,
array('Dr.','Mr.','Mrs.','Ms.'));
echo selectDateEntry('Birth date','Birth',
$dbEntries['BirthMonth'],
$dbEntries['BirthDay'],
$dbEntries['BirthYear'],
$errors);
echo selectDateEntry('Hire date','Hire',
$dbEntries['HireMonth'],
$dbEntries['HireDay'],
$dbEntries['HireYear'],
$errors);
echo textEntry('Address','Address',$dbEntries,$errors,50);
echo textEntry('City','City',$dbEntries,$errors,30);
echo textEntry('Region','Region',$dbEntries,$errors,2);
echo textEntry('Postal Code','PostalCode',$dbEntries,$errors,10);
echo textEntry('Country','Country',$dbEntries,$errors,5);
echo textEntry('Home phone','HomePhone',$dbEntries,$errors,15);
echo textEntry('Extension','Extension',$dbEntries,$errors,5);
echo textAreaEntry('Notes','Notes',$dbEntries,$errors,50,3);
echo selectEntry('Manager','ReportsTo',$mgrEntries,
$errors,
$dbEntries['ReportsTo']);
echo pwEntry('Password1','Password2',$errors,10);
?>
<tr>
<td colspan="2"><input type="submit" value="Add Employee"></td>
</tr>
</table>
</form>
This file creates the entry form. Notice that it creates entry rows through calls to functions in the
fnFormPresentation.php file. This allows us to easily incorporate error handling and error
messages into the form entries without making the HTML form itself difficult to maintain.

Example

ReusingCode/Demos/Includes/ProcessEmployee.php
<?php
$dbEntries['FirstName'] = dbString($_POST['FirstName']);
$dbEntries['LastName'] = dbString($_POST['LastName']);
$dbEntries['Title'] = ucwords(dbString($_POST['Title']));
$dbEntries['Address'] = dbString($_POST['Address']);
$dbEntries['City'] = dbString($_POST['City']);
$dbEntries['Region'] = dbString($_POST['Region']);
$dbEntries['PostalCode'] = dbString($_POST['PostalCode']);
$dbEntries['Country'] = dbString($_POST['Country']);
$dbEntries['HomePhone'] = dbString($_POST['HomePhone']);
$dbEntries['Extension'] = dbString($_POST['Extension']);
$dbEntries['Notes'] = dbString($_POST['Notes']);
$dbEntries['ReportsTo'] = $_POST['ReportsTo'];
$dbEntries['Password'] = dbString($_POST['Password1']);
$dbEntries['Email'] = dbString($_POST['Email']);
$dbEntries['BirthMonth'] = dbString($_POST['BirthMonth']);
$dbEntries['BirthDay'] = dbString($_POST['BirthDay']);
$dbEntries['BirthYear'] = dbString($_POST['BirthYear']);
$dbEntries['HireMonth'] = dbString($_POST['HireMonth']);
$dbEntries['HireDay'] = dbString($_POST['HireDay']);
$dbEntries['HireYear'] = dbString($_POST['HireYear']);

if (!checkLength($_POST['FirstName']))
{
$errors['FirstName'] = 'First name omitted.';
}
else
{
$browserEntries['FirstName'] = browserString($_POST['FirstName']);
}

if (!checkLength($_POST['LastName']))
{
$errors['LastName'] = 'Last name omitted.';
}
else
{
$browserEntries['LastName'] = browserString($_POST['LastName']);
}
if (!checkLength($_POST['Title']))
{
$errors['Title'] = 'Title omitted.';
}
else
{
$browserEntries['Title'] = ucwords(browserString($_POST['Title']));
}

if ( array_key_exists('TitleOfCourtesy',$_POST) )
{
$browserEntries['TitleOfCourtesy'] =
browserString($_POST['TitleOfCourtesy']);
$dbEntries['TitleOfCourtesy'] = dbString($_POST['TitleOfCourtesy']);
}
else
{
$errors['TitleOfCourtesy'] = 'Title of Courtesy not selected.';
}

if (!checkdate($_POST['BirthMonth'],$_POST['BirthDay'],$_POST['BirthYear']))
{
$errors['BirthDate'] = 'Birth date is not a valid date.';
}

if (!checkdate($_POST['HireMonth'],$_POST['HireDay'],$_POST['HireYear']))
{
$errors['HireDate'] = 'Hire date is not a valid date.';
}

if (!checkLength($_POST['Address'],5,200))
{
$errors['Address'] = 'Address omitted.';
}
else
{
$browserEntries['Address'] = browserString($_POST['Address']);
}

if (!checkLength($_POST['City'],1,100))
{
$errors['City'] = 'City omitted.';
}
else
{
$browserEntries['City'] = browserString($_POST['City']);
}

if (!checkLength($_POST['Region'],2,2) && !checkLength($_POST['Region'],0,0))


{
$errors['Region'] = 'Region name must be two characters.';
}
else
{
$browserEntries['Region'] = browserString($_POST['Region']);
}

if (!checkLength($_POST['PostalCode']))
{
$errors['PostalCode'] = 'Postal Code omitted.';
}
else
{
$browserEntries['PostalCode'] = browserString($_POST['PostalCode']);
}

if (!checkLength($_POST['Country']))
{
$errors['Country'] = 'Country omitted.';
}
else
{
$browserEntries['Country'] = browserString($_POST['Country']);
}

if (!checkLength($_POST['HomePhone'],10,15))
{
$errors['HomePhone'] = 'Home phone must be between 10 and 15 characters.';
}
else
{
$browserEntries['HomePhone'] = browserString($_POST['HomePhone']);
}

if (!checkLength($_POST['Extension'],3,5))
{
$errors['Extension'] = 'Extension must be between 3 and 5 characters.';
}
else
{
$browserEntries['Extension'] = browserString($_POST['Extension']);
}

if (!checkLength($_POST['Notes'],0,100))
{
$errors['Notes'] = 'Notes must be fewer than 100 characters:<br>
<span style="color:blue; font-weight:normal">' .
browserString(substr($_POST['Notes'],0,100)) .
'</span><span style="color:red; font-weight:normal;
text-decoration:line-through;">' .
browserString(substr($_POST['Notes'],100)) .
'</span>';
}
else
{
$browserEntries['Notes'] = browserString($_POST['Notes']);
}

if ($_POST['ReportsTo'] == 0)
{
$errors['ReportsTo'] = 'Manager not selected.';
}
else
{
$browserEntries['ReportsTo'] = $_POST['ReportsTo'];
}

if ( !checkPassword($_POST['Password1'],$_POST['Password2']) )
{
$errors['Password'] = 'Passwords do not match or are not the right length.';
}
else
{
$browserEntries['Password'] = browserString($_POST['Password1']);
}

if ( !checkEmail($_POST['Email']) )
{
$errors['Email'] = 'Email is invalid.';
}
else
{
$browserEntries['Email'] = browserString($_POST['Email']);
}
?>
<?php
if (!count($errors))
{
$showForm = false;
?>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Confirmed" value="true">
<?php
echo '<h2>Confirm Entries</h2>';
echo '<ol>';
foreach ($browserEntries as $key=>$entry)
{
if ($key=='ReportsTo')
{
echo "<li><b>Manager:</b> $mgrEntries[$entry]</li>";
}
else
{
echo "<li><b>$key:</b> $entry</li>";
}
}
echo '</ol>';

foreach ($dbEntries as $key=>$entry)


{
?>
<input type="hidden" name="<?php echo $key ?>"
value="<?php echo $entry ?>">
<?php
}
?>
<input type="submit" value="Confirm">
</form>
<?php
}
else
{
$dbEntries = $_POST;
}
?>

This file contains code for processing the form entries. It makes use of functions in the
fnFormValidation.php file for validating entries. If no errors are found, it sets the boolean
$showForm to false, so that the original form will not be displayed and it outputs all the entries
(made browser-safe) to the browser for confirmation.

If errors are found, it adds them to the $errors array, which is passed into the form presentation
functions, so that they can return code for displaying the errors. If there are errors, the boolean
$showForm is left as true, so that the original form is redisplayed.

2.13 MANAGING DATA

In this concept, you will learn how to access a database in PHP.

Lesson Goals
 Retrieve and safely display records from a database.
 Insert new records into a database.
 Update existing records in a database.

2.13.1 Querying a Database

The steps for querying a database in a PHP script are as follows:

1. Connect to the database.


2. Send query to the database.
3. Retrieve and store results sent back from the database.
4. Output the results of the query to the browser.
5. Free up resources and disconnect from the database.

mysqli() Overview

New in PHP5 is the mysqli library, which works with MySQL versions 4.1.3 and above and
takes advantage of a new faster connection protocol in MySQL. The mysqli library provides two
interfaces: an object-oriented interface and a procedural interface. The following two scripts use
the two different interfaces to accomplish the same result.

Example

ManagingData/Demos/SimpleQuery-OO.php
<html>
<head>
<title>Simple Query - OO</title>
</head>
<body>
<?php
@$db = new mysqli('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$query = 'SELECT * FROM Employees';
$result = $db->query($query);
$numResults = $result->num_rows;

echo "<b>$numResults Employees</b>";


?>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th>Email</th>
<th>Extension</th>
</tr>
<?php
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Title'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td align="right">x' . $row['Extension'] . '</td>';
echo '</tr>';
}
?>
</table>
<?php
$result->free();
$db->close();
}
?>
</body>
</html>

Example

ManagingData/Demos/SimpleQuery-Procedural.php

<html>
<head>
<title>Simple Query - Procedural</title>
</head>
<body>
<?php
@$db = mysqli_connect('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$query = 'SELECT * FROM Employees';
$result = mysqli_query($db,$query);
$numResults = mysqli_num_rows($result);

echo "<b>$numResults Employees</b>";


?>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th>Email</th>
<th>Extension</th>
</tr>
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo '<tr>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Title'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td align="right">x' . $row['Extension'] . '</td>';
echo '</tr>';
}
?>
</table>
<?php
mysqli_free_result($result);
mysqli_close($db);
}
?>
</body>
</html>
1. To connect to the database, we use:
o Object-oriented: @$db = new mysqli('localhost','root','pwdpwd','Northwind');
o Procedural: @$db = mysqli_connect('localhost','root','pwdpwd','Northwind');
2. To see if the connection was successful we check mysqli_connect_errno(), which returns
an error number if there is a connection error or 0 if there is no error. If an error occurs,
we output a message with mysqli_connect_error(). We use the procedural interface in
both cases, because a connection object doesn't get created if the connection fails.
3. To send the query to the database and store the results in a variable, we use:
o Object-oriented: $result = $db->query($query);
o Procedural: $result = mysqli_query($db,$query);
4. To output the results of the query, we use:
o Object-oriented:

while ($row = $result->fetch_assoc())


{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td align='right'>x" . $row['Extension'] . "</td>";
echo "</tr>";
}

o Procedural:

while ($row = mysqli_fetch_assoc($result))


{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td align='right'>x" . $row['Extension'] . "</td>";
echo "</tr>";
}

5. To free up resources and disconnect from the database, we use:


o Object-oriented:

$result->free();
$db->close();

o Procedural:

mysqli_free_result($result);
mysqli_close($db);

mysqli Methods and Properties

Connection Methods and Properties

Object-oriented Procedural Description

new mysqli() mysqli_connect() Connects to a MySQL server.

mysqli_connect_errno() Returns connection error


number or 0 if there's no error

mysqli_connect_error() Returns connection error


message

$db->host_info mysqli_get_host_info() Returns information on the


connection

Query Functions
Object-oriented Procedural Description

$db->query() mysqli_query() Sends a query to


the database and
returns results.

$db->multi_query() mysqli_multi_query() Sends multiple


queries to the
database and
returns results.

Fetch Functions

Object-oriented Procedural Description

$result->fetch_row() mysqli_fetch_row() Returns a result row from a


query result object or resource
as an indexed array.

$result->fetch_assoc() mysqli_fetch_assoc() Returns a result row from a


query result object or resource
as an associative array

$result->fetch_object() mysqli_fetch_object() Returns a result row from a


query result object or resource
as an object.

2.13.2 PHP-MYSQL FUNCTIONS

 mysql_connect()
 It is used to Open a connection to a MySQL Server.
 This function returns the connection on success, or FALSE and an error on failure. You
can hide the error output by adding an '@' in front of the function name.
SYNTAX
mysql_connect([host][, user_name][, password]);

PARAMETER
Name Description

Host Optional. The MySql server. You can use hostname, ip address,
hostname:portname, ip address:portname as server. Default is
localhost:3306.
Username Optional.The username. Default value is defined by
mysql.default_user.
password Optional. The password of the user. Default value is defined by
mysql.default_password.

EXAMPLE
<?php
$continued = mysql_connect("localhost","root","");
if ($continued)
{ echo ("Connection is succeed"); }
else
{ echo ("Connection is fail"); } ?>
Output  Connection is succeed

 mysql_close()
 The mysql_close() function closes a non-persistent MySQL connection.
 This function returns TRUE on success, or FALSE on failure.
SYNTAX
mysql_close(connection)

PARAMETER

Parameter Description

connection Optional. Specifies the MySQL connection to close. If not specified,


the last connection opened by mysql_connect() is used.

EXAMPLE
<?php
$con=mysql_connect('localhost', 'root', '');
if ($con)
{ echo "connected successfully"; }
mysql_close($con);
if ($con)
{ echo "<br />disconnected successfully"; } ?>
Output  connected successfully
disconnected successfully

 mysql_error()
 The mysql_error() function is used to get the error message from the last MySQL
operation.

 This function returns an empty string ("") if no error occurs.

SYNTAX
mysql_error(connection)

PARAMETER
Parameter Description
Connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.

EXAMPLE

<?php
$con = mysql_connect("localhost", "root", "");
if (!mysql_select_db("tutorials", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con). "<br />"; }
mysql_select_db("tutorials", $con);
if (!mysql_query("select * from test", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con) . "<br />"; }
?>
 msyql_errno()
 The mysql_errno() function returns the error number of the last MySQL operation.
 This function returns 0 (zero) if no error has occurred.

SYNTAX
mysql_errno(connection)

PARAMETER

Parameter Description

Connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
if (!mysql_select_db("tutorials", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con). "<br />"; }
mysql_select_db("tutorials", $con);
if (!mysql_query("select * from test", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con) . "<br />"; } ?>
Output -> 1049: Unknown database 'tutorials'
1046: No database selected

 mysql_select_db()
 The mysql_select_db() function sets the current active database on the server which is
associated with the specified connection.

 This function returns TRUE on success, or FALSE on failure.

SYNTAX:
mysql_select_db(database,connection)
PARAMETER

Parameter Description

database Required. Specifies the database to select.


connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.

EXAMPLE
<?php
$con = mysql_connect("localhost","root","");
$selected_db = mysql_select_db("test");
if (!$selected_db)
{ die ('Database not selected : ' . mysql_error()); }
else
{ echo "Database Selected"; } ?>
Output
Database Selected

 mysql_query()
 The mysql_query() is used to execute query on the default database.
 This function returns the query handle for SELECT queries, TRUE/FALSE for other
queries, or FALSE on failure.
SYNTAX
mysql_query(query,connection)

PARAMETER

Parameter Description

Query Required. Specifies the SQL query to send (should not end with a
semicolon)
Connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.

EXAMPLE
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{ die('Could not connect: ' . mysql_error()); }
$sql = "SELECT * FROM demo";
mysql_query($sql,$con);
// some code
mysql_close($con); ?>
 mysql_fetch_array()
 The mysql_fetch_array() is used to retrieve a row of data as an array from a MySQL
result handle.
 This function gets a row from the mysql_query() function and returns an array on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_array(data,array_type)

PARAMETER
Parameter Description
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
array_type Optional. Specifies what kind of array to return.
Possible values:
MYSQL_ASSOC - Associative array
MYSQL_NUM - Numeric array
MYSQL_BOTH - Default.
Both associative and numeric array

EXAMPLE

<?php
$con = mysql_connect("localhost", "root", "") or die("Could not connect: " .
mysql_error());
mysql_select_db("test");
$result = mysql_query("select * from demo");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Id</th><th>Name</th><th>Pincode</th>";
while ($row = mysql_fetch_array($result))
{ echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['stdname']."</td>";
echo "<td>".$row['pincode']."</td>";
echo "</tr>"; } ?>
Output
 mysql_num_rows()
 The mysql_num_rows() is used to get the number of rows in a MySQL result handle.

 This function returns FALSE on failure.

SYNTAX:
mysql_num_rows(data)

PARAMETER
Paramete Description
r
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
$result = mysql_query("select * from demo");
$number_of_rows = mysql_num_rows($result);
echo "Number of rows fetched are : ". $number_of_rows;
?>
Output
Number of rows fetched are : 2

 mysql_affected_rows()
 The mysql_affected_rows() function returns the number of affected rows in the previous MySQL
operation.

 This function returns the number of affected rows on success, or -1 if the last operation
failed.

SYNTAX
mysql_affected_rows(connection)
PARAMETER
Parameter Description
Connectio Optional. Specifies the MySQL connection. If not specified, the last
n connection opened by mysql_connect() or mysql_pconnect() is used.

EXAMPLE
<?php
$con=mysql_connect('localhost', 'root', '');
mysql_select_db("test")or die("cannot select DB");
mysql_query("insert into demo(id,stdname,pincode) values(1,'html',123456)");
mysql_query("insert into demo(id,stdname,pincode) values(2,'html',123456)");
echo "Inserted records:".mysql_affected_rows();
echo "<br />It shows 1 if the new rows are inserted"; ?>
Output
Inserted records:1
It shows 1 if the new rows are inserted
Other Example
mysql_query("DELETE FROM demo WHERE id='1'");
$rc = mysql_affected_rows();
echo "Records deleted: " . $rc;
Output  Records deleted: 1

 mysql_fetch_assoc()
 The mysql_fetch_assoc() used to retrieve a row of data as an associative array from a
MySQL result handle.
 This function gets a row from the mysql_query() function and returns an array on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_assoc(data)

PARAMETER
Paramete Description
r
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "") or die("Could not connect: " .
mysql_error());
mysql_select_db("test");
$result = mysql_query("select * from demo");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Id</th><th>Name</th><th>Pincode</th>";
while ($row = mysql_fetch_assoc($result))
{
echo"<tr><td>".$row['id']."</td><td>".$row['stdname']."</td><td>".
$row['pincode']."</td></tr>";
}
echo "</table>";
 mysql_fetch_field()
 The mysql_fetch_field() function is used to get the column information of a field from a
result handle.
o POSSIBLE RETURN VALUES:
 name - Field name
 table - The table the field belongs to
 def - Default value for the field
 max_length - Maximum field length
 not_null - 1 if the field cannot be NULL
 primary_key - 1 if the field is a primary key
 unique_key - 1 if the field is a unique key
 multiple_key - 1 if the field is a non-unique key
 numeric - 1 if the field is numeric
 blob - 1 if the field is a BLOB
 type - Field type
 unsigned - 1 if the field is unsigned
 zerofill - 1 if the field is zero-filled

SYNTAX

mysql_fetch_field (result, field_offset)

PARAMETER
Parameter Description
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
field_offse Optional. Specifies which field to start returning. 0 indicates the first
t field. If this parameter is not set, it will retrieve the next field
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{ die('Could not connect: ' . mysql_error()); }

$db_selected = mysql_select_db("test",$con);
$sql = "SELECT * from demo";
$result = mysql_query($sql,$con);
while ($property = mysql_fetch_field($result))
{
echo "Field name: " . $property->name . "<br />";
echo "Table name: " . $property->table . "<br />";
echo "Default value: " . $property->def . "<br />";
echo "Max length: " . $property->max_length . "<br />";
echo "Not NULL: " . $property->not_null . "<br />";
echo "Primary Key: " . $property->primary_key . "<br />";
echo "Unique Key: " . $property->unique_key . "<br />";
echo "Mutliple Key: " . $property->multiple_key . "<br />";
echo "Numeric Field: " . $property->numeric . "<br />";
echo "BLOB: " . $property->blob . "<br />";
echo "Field Type: " . $property->type . "<br />";
echo "Unsigned: " . $property->unsigned . "<br />";
echo "Zero-filled: " . $property->zerofill . "<br /><br />"; }
mysql_close($con); ?>

 mysql_fetch_object()
 The mysql_fetch_object() function returns a row from a recordset as an object.
 This function gets a row from the mysql_query() function and returns an object on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_object(data)

PARAMETER
Paramete Description
r
Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function

EXAMPLE
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$result = mysql_query("select * from demo");
while ($row = mysql_fetch_object($result))
{ echo $row->stdname."<br />"; }
mysql_free_result($result); ?>
Output
project
 mysql_fetch_row()
 The mysql_fetch_row() function returns a row from a recordset as a numeric array.
 This function gets a row from the mysql_query() function and returns an array on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_row(data)

PARAMETER
Parameter Description

data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function

EXAMPLE

<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{ die('Could not connect: ' . mysql_error()); }

$db_selected = mysql_select_db("test",$con);
$sql = "SELECT * from demo WHERE name='pradip'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));
mysql_close($con); ?>
Output
Array ( [0] => 1 [1] => pradip [2] => rajkot )

 mysql_insert_id()
 The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the
previous INSERT operation.
 This function returns 0 if the previous operation does not generate an
AUTO_INCREMENT ID, or FALSE on MySQL connection failure.
SYNTAX
mysql_insert_id(connection)

PARAMETER
Paramete Description
r

connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
mysql_query("INSERT INTO demo(id, name,city) values (3,'vsc-
project','rajkot')");
echo "Last inserted record has id : ". mysql_insert_id();
?>
Output
Last inserted record has id : 3

 mysql_num_fields()
 The mysql_num_fields() function returns the number of fields in a recordset.

 This function returns FALSE on failure.

SYNTAX
mysql_num_fields(data)

PARAMETER
Paramete Description
r

data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
$result = mysql_query("select id,name,city from demo where id = '1'");
echo mysql_num_fields($result);
?>
Output
3

 mysql_result()
 The mysql_result() function returns the value of a field in a recordset.
 This function returns the field value on success, or FALSE on failure.

SYNTAX
mysql_result(data,row,field)

PARAMETER
Parameter Description

data Required. Specifies which result handle to use. The data pointer is the
return from the mysql_query() function

row Required. Specifies which row number to get. Row numbers start at 0

field Optional. Specifies which field to get. Can be field offset, field name or
table.fieldname. If this parameter is not defined mysql_result() gets the
first field from the specified row

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$db_selected = mysql_select_db("test_db", $con);
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
echo mysql_result($result,0);
mysql_close($con);
?>
 mysql_tablename()
 Retrieves the table name from result.
SYNTAX
string mysql_tablename ( resource result, int row)

PARAMETER
Parameter Description

result Required. A result pointer resource that's returned from


mysql_list_tables().

row Required. The integer index (row/table number)

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$list = mysql_list_tables("test");
$i = 0;
while ($i < mysql_num_rows ($list)) {
$tb_names[$i] = mysql_tablename ($list, $i);
echo $tb_names[$i] . "<BR>";
$i++; } ?>
Output
demo
login
student_master

 mysql_list_tables()
 Lists the tables in a MySQL database.

SYNTAX
mysql_list_tables(database[, connection]);

PARAMETER
Parameter Description

Database Required.The name of the database


Connectio Optional. The MySQL connection.
n

EXAMPLE
<?php
$dbname = 'test';
if (!mysql_connect('localhost', 'root', ''))
{
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit; }

while ($row = mysql_fetch_row($result)) {


echo "Table: {$row[0]}<br>"; } ?>

Output
Table: demo
Table: login
Table: student_master

 mysql_list_fields()
 Fetches information about the fields in a table.
SYNTAX
mysql_list_fields(database, table[, connection]);

PARAMETER
Parameter Description

Database Required. Database to use.

Table Required.Table to use.

connection Optional.The MySQL connection.


EXAMPLE
<?php
$link = mysql_connect("localhost", "root", "")or die ("Could not connect");
$fields = mysql_list_fields("test", "demo", $link);
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {
echo mysql_field_name($fields, $i) . "<br>";
} ?>
Output
id
name
city

 mysql_field_type()
 The mysql_field_type() function is used to get the type of the specified field in a result.
SYNTAX
mysql_field_type(data,field_offset)

PARAMETER
Parameter Description

Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function

field_offset Required. Specifies which field to start on. 0 indicates the first field

EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
$result = mysql_query("select * from demo");
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table_name = mysql_field_table($result, 0);
echo $table_name . "' table has " . $fields . " fields and " . $rows . " record(s)<br />";
echo "<p>Here is the list of the fields:</p>";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "<br /> "; } ?>
Output
demo' table has 3 fields and 3 record(s)
Here is the list of the fields:
int id 10 not_null primary_key auto_increment
string name 20 not_null
 mysql_db_name()
 The mysql_db_name() function retrieve the database name from a call to the
mysql_list_dbs() function.
SYNTAX
mysql_db_name(result, row, field)

PARAMETER
Paramete Description
r

result Required. The result pointer from a call to mysql_list_dbs().

row Required. The index into the result set.

field Optional. The field name.

EXAMPLE
<?php
$con=mysql_connect('localhost', 'root', '');
$db_list = mysql_list_dbs($con);
$i = 0;
$no_of_rows = mysql_num_rows($db_list);
echo "<h2>List of databases</h2>";
while ($i < $no_of_rows)
{
echo mysql_db_name($db_list, $i) . "<br />";
$i++; } ?>
Output
List all database available in your mysql server.

 mysql_db_query()
 Queries a MySQL database.
SYNTAX
mysql_db_query(database, query[, connection]);
PARAMETER
Paramete Description
r

database Required. Database to query

query Required. Query to make on the database

connection The MySQL connection.

EXAMPLE
<?php
// Attempt to connect to the default database server
$link = mysql_connect("localhost", "root", "")
or die ("Could not connect");
$sql = 'SELECT * FROM tblState';
// run a 'select' on the 'system' database
$data = mysql_db_query('system', $sql, $link);
mysql_close($link) ; ?>

 mysql_data_seek()
 The mysql_data_seek() function moves the internal row pointer.
 The internal row pointer is the current row position in a result returned by the
mysql_query() function.
 This function returns TRUE on success, or FALSE on failure.
SYNTAX
mysql_data_seek(data,row)

PARAMETER
Paramete Description
r

Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function

Row Required. Specifies which record to move to. 0 indicates the first record

EXAMPLE
<?php
$connection = mysql_connect("localhost", "root", "");
if (!$connection)
{ die('Could not connect: ' . mysql_error()); }
else
{ $db_selected = mysql_select_db("test",$connection);
$sql = "SELECT * from demo";
2.13.3 Insert Record in mysql using PHP

We can insert record using php, mysql. mysql is used to store the data and php is used to send the
query to mysql database. Below example give the full details about how to insert record in mysql
using php.

Example 1:
registration.php

<?php
echo $pass=rand();
$epass=md5($pass);
$con=mysql_connect("localhost","root","");
mysql_select_db('project',$con);

$sql="insert into registration(fname,lname,emailid,password,status,role)values('".


$_POST['fnm']."','".$_POST['lnm']."','".$_POST['emailid']."','$epass','a','u')";
mysql_query($sql);
?>

<body>
<form method="post">
<table align="center" border="1">
<tr>
<td>First Name</td>
<td><input type="text" name="fnm" />
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lnm" />
</tr>

<tr>
<td>EmailId</td>
<td><input type="text" name="emailid" />
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
<td><input type="reset" name="reset" /></td>
</tr>
</table>
</form>
</body>
</html>

database
Example 2:

Insert.php

<html>
<head>
<title>Untitled Document</title>
</head>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("demo");
echo $hb=$_POST['txtchk1']." ".$_POST['txtchk2']." ".$_POST['txtchk3'];

$sql="insert into stud(name,city,pincode,gender,hobby,branch,address)


values('".$_POST['fname']."','".$_POST['txtcity']."',".$_POST['pincode'].",'".
$_POST['txtgen']."','".$hb."','".$_POST['txtbranch']."','".$_POST['txtadd']."')";

mysql_query($sql);

?>

<body>
<form method="post">
<table align="center" border="1">
<tr>

<td>First Name:</td>
<td><input type="text" name="fname"></td>
</tr>

<tr>
<td>City:</td>
<td><input type="text" name="txtcity"></td>
</tr>

<tr>
<td>Pincode:</td>
<td><input type="text" name="pincode"></td>
</tr>

<tr>
<td>Gender:</td>
<td>F:<input type="radio" name="txtgen" value="F">

M:<input type="radio" name="txtgen" value="M">


</td>
</tr>
<tr>
<td>Hobby:</td>
<td>
Read:<input type="checkbox" name="txtchk1" value="Read">
Playing:<input type="checkbox" name="txtchk2" value="Playing">
Other:<input type="checkbox" name="txtchk3" value="Other">
</td>
</tr>
<tr>
<td>Branch:</td>
<td>
<select name="txtbranch">
<option>BCA</option>
<option>BIT</option>
<option>PGDCA</option>

</select>

</td>

</tr>

<tr>
<td>Address:</td>
<td><textarea name="txtadd"></textarea> </td>

</tr>
<tr>

<td><input type="submit" name="submit" value="Submit"></td>


<td><input type="reset" name="reset" value="Cancle"></td>

</tr>
</table>

</form>
</body>
</html>
2.13.4 Delete Record Using php Mysql with Javascript Confirm Box

Method 1 to Delete the Record


Display.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script language="javascript">

function del_rec(id)
{

if(confirm("Do you wnat to delete this record...?"))


{

window.location="display.php?did="+id;
}
}
</script>
</head>

<body>
<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_GET['did']))
{
mysql_query("delete from stud where id=".$_GET['did']."");

}
$sql="select * from stud";
$nsql=mysql_query($sql);
?>
<table border="1">
<tr>
<td><b>Id</b></td>
<td><b>Name</b></td>
<td><b>Delete</b></td>
</tr>
<?php
while($row=mysql_fetch_array($nsql))
{
?>
<tr>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row[1]; ?></td>
<td><a href="#" onclick="del_rec(<?php echo $row[0]; ?>)">Delete</td>
</tr>

<?php
}
?>
</table>
</body>
</html>

Database
Method 2 to Delete the Record

delete.php

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("test");
$sql=mysql_query("select * from stud");

if(isset($_REQUEST[did]))
{
mysql_query("delete from stud where id=".$_REQUEST[did]);
?>
<script language="javascript">
window.location="delete.php";
</script>
<?php
}

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>

<table width="200" border="1">


<?php
while($row=mysql_fetch_array($sql))
{
?>
<tr>
<td rowspan="3">
<img src="<?php echo "img/".$row["image"]; ?>" height="100px" width="180px" /></td>
<td><?php echo $row["id"]; ?></td>
<td rowspan="3"><a href="delete.php?did=<?php echo $row["id"]; ?>" onclick="return
confirm('are sure to delete!')">Delete</a></td>
</tr>
<tr>
<td><?php echo $row["name"]; ?></td>
</tr>
<tr>
<td><?php echo $row["pincode"]; ?></td>
</tr>
<?php } ?>
</table>

</body>
</html>

Database
update record in php and mysql

<html>
<head>
</head>

<body>
<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("test");

if(isset($_POST['submit']))
{
$sql="update stud set name='".$_POST['txtnm']."',city='".$_POST['txtct']."' where id=".
$_GET['uid']."";
mysql_query($sql);
?>
<?php

$sql="select * from stud where id=".$_GET['uid']."";


$qsql=mysql_query($sql);

$row=mysql_fetch_array($qsql)
?>

<form method="post">
<table border="1" align="center">
<tr>
<td>Name:</td>
<td><input type="text" name="txtnm" value="<?php echo $row['1']; ?>"></td>
</tr>

<tr>
<td>City:</td>
<td><input type="text" name="txtct" value="<?php echo $row['2']; ?>"></td>
</tr>

<tr>
<td><input type="submit" name="submit" value="Update"></td>
<td><input type="reset" name="reset" value="Cancle"></td>
</tr>

</table>
</form>
</body>
</html>

Main Page:
Update Page

Searching Record
Search.html

<html>

<head> <title>search record</title>

<body>

<form action=”search.php” method=”post”>

Enter Roll no to view <input type=text name=en><br>

</body>

</html>

Search.php

<html>

<head> <title>search record</title>

<body>

<?php

$n=$_POST[‘en’];

$cn=mysql_connect(“localhost”) or die(mysql_error());
mysql_select_db(“sybca”, $cn) or die(mysql_error());

$rs=mysql_query(“select * from student where rollno=$n”, $cn) or die(mysql_error());

If(mysql_num_rows($rs)>=1)

echo “rollno :-“ . $row[‘rollno’]; // rollno is name of column of table student

echo “<br>”;

echo “Name :-“ . $row[‘sname’]; // sname is name of column of table student

echo “<br>”;

echo “Address :-“ . $row[‘address’]; // address is name of column of table student

echo “<br>”;

echo “email :-“ . $row[‘email’]; // email is name of column of table student

else

echo “No record found”;

mysql_close($cn);

?>

</body>

</html>
2.14 REGULAR EXPRESSIONS

 Regular expressions are nothing more than a sequence or pattern of characters it. They
provide the foundation for pattern-matching functionality.
 Using regular expression you can search a particular string inside an another string, you
can replace one string by another string and you can split a string into many chunks.
 In a regular expression, most characters match only themselves. For instance, if you
search for the regular expression "foo" in the string "John plays football," you get a
match because "foo" occurs in that string. Some characters have special meanings in
regular expressions. For instance, a dollar sign ($) is used to match strings that end with
the given pattern. Similarly, a caret (^) character at the beginning of a regular expression
indicates that it must match the beginning of the string. The characters that match
themselves are called literals. The characters that have special meanings are called
metacharacters.
 The dot (.) metacharacter matches any single character except newline (\). So, the pattern
h.t matches hat, hothit, hut, h7t, etc. The vertical pipe (|) metacharacter is used for
alternatives in a regular expression. It behaves much like a logical OR operator and you
should use it if you want to construct a pattern that matches more than one set of
characters. For instance, the pattern Utah|Idaho|Nevada matches strings that contain
"Utah" or "Idaho" or "Nevada". Parentheses give us a way to group sequences. For
example, (Nant|b)ucket matches "Nantucket" or "bucket". Using parentheses to group
together characters for alternation is called grouping.
 If you want to match a literal metacharacter in a pattern, you have to escape it with a
backslash.
 To specify a set of acceptable characters in your pattern, you can either build a character
class yourself or use a predefined one. A character class lets you represent a bunch of
characters as a single item in a regular expression. You can build your own character
class by enclosing the acceptable characters in square brackets. A character class matches
any one of the characters in the class. For example a character class [abc] matches a, b or
c. To define a range of characters, just put the first and last characters in, separated by
hyphen. For example, to match all alphanumeric characters: [a-zA-Z0-9]. You can also
create a negated character class, which matches any character that is not in the class. To
create a negated character class, begin the character class with ^: [^0-9].
 The metacharacters +, *, ?, and {} affect the number of times a pattern should be
matched. + means "Match one or more of the preceding expression", * means "Match
zero or more of the preceding expression", and ? means "Match zero or one of the
preceding expression". Curly braces {} can be used differently. With a single integer, {n}
means "match exactly n occurrences of the preceding expression", with one integer and a
comma, {n,} means "match n or more occurrences of the preceding expression", and with
two comma-separated integers {n,m} means "match the previous character if it occurs at
least n times, but no more than m times".

 PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression. You can use any of them based on
your comfort.

2.14.1 REGULAR EXPRESSION TYPES

o POSIX EXTENDED
o PERL COMPATIBLE

2.14.2 REGULAR EXPRESSION SYNTAX


o ^ – Start of string
o $ – End of string
o . – Any single character
o ( ) – Group of expressions
o [] – Item range ( e.g. [afg] means a, f, or g )
o [^] – Items not in range ( e.g. [^cde] means not c, d, or e )
o – (dash) – character range within an item range ( e.g. [a-z] means a through z )
o | (pipe) – Logical or ( e.g. (a|b) means a or b )
o ? – Zero or one of preceding character/item range
o * – Zero or more of preceding character/item range
o + – One or more of preceding character/item range
o {integer} – Exactly integer of preceding character/item range ( e.g. a{2} )
o {integer,} – Integer or more of preceding character/item range ( e.g. a{2,} )
o {integer,integer} – From integer to integer (e.g. a{2,4} means 2 to four of a )
o \ – Escape character
o [:punct:] – Any punctuation
o [:space:] – Any space character
o [:blank:] – Any space or tab
o [:digit:] – Any digit: 0 through 9
o [:alpha:] – All letters: a-z and A-Z
o [:alnum:] – All digits and letters: 0-9, a-z, and A-Z
o [:xdigit:] – Hexadecimal digit
o [:print:] – Any printable character
o [:upper:] – All uppercase letters: A-Z
o [:lower:] – All lowercase letters: a-z

2.14.3 CHARACTER CLASSES:


o \c – Control character
o \s – Whitespace
o \S – Not whitespace
o \d – Digit (0-9)
o \D – Not a digit
o \w – Letter, Digit, Underscore [a-zA-Z0-9_]
o \W – Not a letter
o \x – Hexadecimal digit
o \O – Octal digit

2.14.4 MODIFIERS:
o i – Case-insensitive
o s – Period matches newline
o m – ^ and $ match lines
o U – Ungreedy matching
o e – Evaluate replacement
o x – Pattern over several lines

2.14.5 POSIX EXTENDED


o The structure of a POSIX regular expression is not dissimilar to that of a typical
arithmetic expression: various elements (operators) are combined to form more
complex expressions.
o The simplest regular expression is one that matches a single character, such as g,
inside strings such as g, haggle, or bag.
o The function ereg is abbreviated as extended regular expression.
o It is the oldest type of regular expression in use.

 THERE ARE DIFFERENT SYMBOLS USED WHICH ARE GIVEN BELOW.

Operator Purpose

* Matches the preceding subexpression zero or more times.


+ Matches the preceding subexpression one or more times.

? Matches the preceding subexpression zero or one time.

^ For starting the format string

$ For ending the format string

[A-Z] Only upper case alphabets.

[a-z] Only lower case alphabets.

[a-z A-Z] Only alphabets in any form.

[0-9] Only digit.

[a-z A-Z 0-9] Alphanumeric characters.

\ Used when any special characters are to be used in the string.

() Used when any more than one value is to be checked.

| For or condition

{n} Is used when the lengths of the digits are known. Where n is an
integer value.

{n,m} n for minimum value and m for maximum value.

 EXAMPLE

Regular Expression Will match…

Foo The string “foo”

^foo “foo” at the start of a string

foo$ “foo” at the end of a string

^foo$ “foo” when it is alone on a string

[abc] a, b, or c

[a-z] Any lowercase letter

(gif|jpg) Matches either “gif” or “jpeg”

[a-z]+ One or more lowercase letters

[0-9.-] Any number, dot, or minus sign


^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _

([wx])([yz]) wy, wz, xy, or xz

[^A-Za-z0-9] Any symbol (not a number or a letter)

([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers

2.14.6 REGEX FUNCTIONS


 PHP has functions to work on complex string manipulation using RegEx. The following
are the RegEx functions provided in PHP.

Function Description

Ereg This function matches the text pattern in a string using a RegEx
pattern.

Eregi This function is similar to ereg(), but ignore the case sensitivity.

ereg_replace This function matches the text pattern in a string using a RegEx
Pattern and replaces it with the given text.

eregi_replace This is similar to ereg_replace(), but ignores the case sensitivity.

Split This function split string into array using RegEx.

Spliti This is similar to Split(), but ignores the case sensitivity.

sql_regcase This function create a RegEx from the given string to make a case
insensitive match.

 EXAMPLE
 Now let us see a simple example to match a US 5 digit zip code from a string
<?php
$zip_pattern = "[0-9]{5}";
$str = "Mission Viejo, CA 92692";
ereg($zip_pattern,$str,$regs);
echo $regs[0];
?>
Output
92692
2.14.7 PERL COMPATIBLE
 Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax
can be used almost interchangeably with the Perl-style regular expression functions. In
fact, you can use any of the quantifiers introduced in the previous POSIX section.
 This type of regular express is developed using the Perl language. The function which is
used for the given regular expression is preg_match() this is perl regular expression.
 The symbols are used as the above ones only. It also returns the Boolean value. If the
format is matched, then it returns true value otherwise will return false value.

 THERE ARE DIFFERENT SYMBOLS USED WHICH ARE GIVEN BELOW.

Symbol Description

\d Any number

\D For anything other that a number

\s Any kind of whitespace.

\S Anything other than than whitespace

\W Any word character (including the underscore character)

\w Anything other than a word character

\A Beginning of string

\b Word boundary

\B Not a word boundary

\Z End of string (matches before final new line of at end of string)

\z End of string (matches only at the very end of the string)

 EXAMPLE
<?php
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$email = "vsc-project@blogspot.com";
if (preg_match($pattern,$email)) echo "Match";
else echo "Not match";
?>
Output  Match
2.14.8 GENERAL FORMAT USING EREG FUNCTION

 EMAIL ADDRESS
/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

 PINCODE
^[0-9]{5,6}$

 MOBILE NUMBER STARTING WITH +91


^\+91[0-9]{10}$

 LAND LINE NUMBER


^[0-9]{4,5}\-[0-9]{7}$

2.14.9 GENERAL FORMAT USING PREG_MATCH FUNCTION

 EMAIL ADDRESS
^\$+(.|_)?\S*\@(yahoo|gmail|co|in|rediff)\.(con|in)$

 PINCODE
^d{5,6}$

 MOBILE NUMBER STRARTING WITH +91


^\+91\d{10}$

 LAND LINE NUMBER


^\d{4,5}\-\d{7}$
2.14.10 SIMPLE VALIDATION FUNCTION IN PHP
<?php
if(isset($_POST["submit"]))
{
if(ereg('^[a-zA-Z]*$',$_POST['txtnm']))
{ $txtnm=""; }
else
{ $txtnm="Enter Valid Name"; }
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",
$_POST['txtdob']))
{
$txtdob="";
}
else
{
$txtdob="Enter Valid DOB";
}

if(ereg('^\+91[0-9]{10}$',$_POST["txtmobileno"]))
{
$txtmobileno="";
}
else
{
$txtmobileno="Enter valid mobile no";
}
if(strlen($_POST["txtpass"])>6)
{
$txtpass="";
}
else
{ $txtpass="Password should not be 6 characters"; }
if (ereg("^[^@]{1,64}@[^@]{1,255}$",$_POST["txtemailid"]))
{ $txtemailid=""; }
else
{ $txtemailid="Enter valid emailid"; } } ?>
<form method="post">
*Sing Mark. Field is must required to fill
<table border="1">
<tr>
<td>*Name</td>
<td><input type="text" name="txtnm" /></td>
<td style="color:#FF0000"><?php if(isset($txtnm)){ echo $txtnm; } ?></td>
</tr>

OUTPUT
 <tr>
<td>Last Name</td>
<td><input type="text" name="txtlnm" /></td>
</tr>

<tr>
<td>Address</td>
<td><textarea name="txtadd"></textarea></td>
</tr>

<tr>
<td>*DOB(yyyy-dd-mm)
<td><input type="text" name="txtdob" /></td>
<td><?php if(isset($txtdob)) { echo $txtdob; } ?></td>
</tr>

<tr>
<td>*Mobile No:(+91)</td>
<td><input type="text" name="txtmobileno" /></td>
<td><?php if(isset($txtmobileno)){ echo $txtmobileno; } ?></td>
</tr>
<tr>
<td>*Email Id</td>
<td><input type="text" name="txtemailid" /></td>
<td style="color:#FF0000"><?php if(isset($txtemailid)) { echo $txtemailid; } ?></td>
</tr>
<tr>
<td>*Password</td>
<td><input type="password" name="txtpass" /></td>
<td><?php if(isset($txtpass)){ echo $txtpass; } ?></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
<td><input type="reset" name="reset" value="Reset"/></td>
</tr>
</table>
</form>
2.15 SESSION
WHAT IS SESSION IN PHP?
 PHP Session is a way to store information in variables that can be used in multiple pages
or across the website during that visit of a user. The php session stored information on
server side unlike cookies, that stores information at user’s computer. Alternatively you
can say PHP session variables scope is global unlike normal variable which scope is
specific to that page or a function.
 As your website becomes more complicated, there will be time when you need to store
information to remember a particular visitor actions or data while navigating to other
pages. A basic HTML site does not allow to store information that can be used across
website. Sessions in PHP provides that mechanism.
 For instance, in an ecommerce site storing shopping cart items, that has been added to
basket during that visit. Users keep on surfing other pages of website, however selected
items are still shown.
 Similarly, storing login in information for a session.The information stored in session
variables is temporary and finishes as sessions ends or dies. For example user has closed
the website.

HOW TO STARTING A PHP SESSION


<?php
//Starting a PHP session
session_start(); ?>

 You simply write the command session_start(); . This command should be placed on top
of the page even before html code. You must have to start the session in order to work
with it.
 So what actually happens when a session is started?
1. PHP creates a random unique identifier string of 32 hexadecimal numbers for that
particular session. e.g. 9d5gpk75d2jj973hjkop2fc934s2578 (php session id).
2. To store that unique identifier a cookies is automatically sent to user’s computer. This
cookie is called PHPSESSID.
3. In the specified temporary directory on the server side a files is automatically created
with prefix sess_[unique identifier code].

WORKING WITH PHP SESSION VARIABLES

<?php
session_start(); // starts php session
$_SESSION['UserID']='1234'; // setting variable values during session
$_SESSION['name']='Pradip';
$_SESSION['location']='Rajkot';
print "session variables are assigned value.<br>";
echo "My ID is: " .$_SESSION['UserID']."<br>";
echo "My Name is: " .$_SESSION['name']. "<br>";
echo "My Location is: " .$_SESSION['location']; ?>
Output
session variables are assigned value.
My ID is: 1234
My Name is: Pradip
My Location is: Rajkot

<?php session_start(); ?>


<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_POST['submit'])&&($_POST['txtuser']!=""))
{
$sql="select * from login where username='".$_POST['txtuser']."' and password='".
$_POST['txtpass']."'";
$nsql=mysql_query($sql);
$nofrow=mysql_num_rows($nsql);
if($nofrow>=1)
{

$_SESSION['user']=$_POST['txtuser'];
?>
<script language="javascript">
Output

PHP SESSION DESTROY

 PHP automatically destroys a session after timeout or user has left the website means
close the browser. You may need to destroy certain variables, which purpose has been
accomplished or a session completely in explicit way.
<?php
session_start();
if(isset($_SESSION[‘UserID’]))
// isset is explained here
unset($_SESSION['UserID']);
unset($_SESSION['name']);
?>
In order to completely destroy a session use following:

<?php
session_start();
session_destroy();
?>

CONFIGURING SESSIONS
o PHP has several configuration directives to control session handling process like session
upload and URL rewriting. These are set with PHP configuration file php.ini.
o PHP SESSION CONFIGURATION DIRECTIVES

SESSION.SAVE_HANDLER
o To set possible handlers to store and retrieve session data. These are
session.save_handler = files | mm | sqlite | user

o Default option is files to handle session data. mm makes RAM to handle session
data. With sqlite option SQLite database is used. Then with user option we can
have custom functions to handle the session.
SESSION.SAVE_PATH
o If the above session.save_handler is set as files, then we need to set the path of
the directory where we want to have session data files. Session.save_path directive is
used to set the path.
o We can also create sub directories to let file storage module to store session files. And
then, we should refer this directory path by specifying its depth. For example,
session.save_path = "N;/path"

o where N is an Integer representing the depth of the sub directory.


o PHP creates session files in the above location with name as current session_id
with sess_ prefix.
o We can set the session files mode by using,
session.save_path = "N;MODE;/path"

o where MODE is an Octal value. The default mode is 600 (allows owner to read
and write).
SESSION.USE_COOKIES
o This directive has 1 or 0 as its value to specify whether cookies are used to store
session id or not.
session.use_cookies = 0 | 1

o If 1 then cookies will be used to store session id. If not, the session id is preserved
by using URL rewriting.
SESSION.COOKIE_SECURE
o It controls whether cookies are sent via secure connections or not. It will be set
with ON | OFF values. The default is OFF.
SESSION.USE_ONLY_COOKIES
o By setting this directive cookies are used as the mandatory storage to preserve
session id. It prevents session hijacking.
SESSION.NAME
o To specify the name of the session. PHPSESSID is the default name.

session.name = PHPSESSID

SESSION.AUTO_START
o We need to start session before using PHP session function. This directive is used
to start session automatically on each page request. So, we need to set
session.auto_start as 1.
session.auto_start = 0 | 1

o If session.auto_start is 1, managing objects into session needs further


configuration. That is, auto_prepend_file directive is used to refer corresponding
class.
SESSION.COOKIE_LIFETIME
o This is used to set cookie life time. If it is set as 0, then cookie remains until
browser restart.
SESSION.COOKIE_PATH
o To specify the path where the cookies will be valid.
SESSION.COOKIE_DOMAIN
o Similarly, to specify the domain in which the cookies will be valid.
SESSION.COOKIE_HTTPONLY
o This directive is on then it will stop client side scripts to access session id
preserved in cookies.
SESSION.GC_PROBABILITY, SESSION.GC_DIVISOR
o The values of these directives are used to calculate the probability to run garbage
collection to clean up session data.
SESSION.GC_MAXLIFETIME
o It has the max lifetime of the session id in seconds. If the session id reaches this
limit, PHP will treat it as garbage and clear it.
SESSION.CACHE_LIMITER
o This directive controls cache headers sent to the client and proxies. The possible
values are,
 none – stops sending cache headers to the client.
 nocache – default option; stop client or proxy to cache page content.
 private – allows only client to cache page content.
 private_no_expire – No expire time is set with the cache header.
 public – allows both client and proxy caching.
SESSION.CACHE_EXPIRE
o It specifies cache expiration time for session enabled pages in seconds.

session.cache_expire = 120
o This directive need not to be set, if session.cache_limiter = nocache.

SESSION.USE_TRANS_SID
o This directive is used to preserve session id by URL rewriting. As URL are shared
among multiple users, maintaining session id in URL is risky. It cause multiple
access with same session_id at a time.
SESSION.HASH_FUNCTION
o This directive is used to choose hash function to generate session id. 0 and 1
represents MD5 and SHA algorithms respectively.

SESSION FUNCTIONS

o session_cache_expire
o Returns current cache expire

o session_cache_limiter
o Get or set the current cache limiter

o session_decode
o Decode session data from a string

o session_encode
o Encodes the current session data as a string

o session_destroy
o Destroys all data registered to a session

o session_get_cookie_params
o Get the session cookie parameters

o session_set_cookie_params
o Set session cookie parameters

o session_id
o Get or set the current session id

o session_name
o Get or set the current session name
o session_register
o Register one or more global variables with the current session

o session_is_registered
o Find whether a global variable is registered

o session_unregister
o Unregister a global variable from the current session

o session_module_name
o Get and/or set the current session module

o session_regenerate_id
o Update the current session id with a newly generated one

o session_save_path
o Get or set the current session file path

o session_set_save_handler
o Set user-level session storage functions

o session_start
o Initialize session data

o session_unset
o Free all session variables currently registered

o session_write_close
o Write session data and end the session

2.16 COOKIE
WHAT IS A COOKIE?
 A cookie is a message given to a Web browser by a Web server. The browser stores the
message in a small text file that the server embeds on the user's computer. Each time the
same computer requests a page with a browser, the cookie is sent back to the server too.
 There are a wide variety of things you can do with cookies. They are used to store
information about user, visited pages, poll results and etc. The main purpose of cookies is to
identify users and possibly prepare customized Web pages for them.

HOW TO CREATE A COOKIE?

 PHP provided setcookie() function to set a cookie. This function requires upto six arguments
and should be called before <html> tag. For each cookie this function has to be called
separately.

 SYNTAX

setcookie(name, value, expire, path, domain, security);

 Here is the detail of all the arguments:


o [name] The cookie name. The name of each cookie sent is stored in the superglobal
array $_COOKIE.
o [value] The cookie value. It is associated with the cookie name.
o [expire] The time after which the cookie should expire in seconds
o [path] Specifies the exact path on the domain that can use the cookies.
o [domain] The domain that the cookie is available. If not domain is specified, the
default value is the value of the domain in which cookie was created.
o [security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies
that the cookie is sent over a secure connection but it doesn't mean that the cookie is
secure. It's just a text file like every other cookie. A value of 0 denotes a standard
HTTP transmission.

 In the example below, we will create a cookie named "name" and assign the value "pradip" to
it. We also specify that the cookie should expire after one hour and that the cookie is
available for all pages within a Tutorials directory.

 EXAMPLE
<?php
setcookie("name", "pradip", time()+3600, "/","", 0);
?>

ACCESSING COOKIES WITH PHP


 Now the cookie is set and we need to retrieve the information. As mentioned above the name
of each cookie sent by your server accessed with the superglobal array $_COOKIE. In the
example below we retrieve the value of the cookie and print out its value on the screen.

 EXAMPLE
<?php
echo $_COOKIE["name"]. "<br />";
?>
Output
pradip

DELETING COOKIE WITH PHP

 By default, the cookies are set to be deleted when the browser is closed. We can override that
default by setting a time for the cookie's expiration but there may be occasions when you need to
delete a cookie before the user closes his browser, and before its expiration time arrives. To do so,
you should assure that the expiration date is in the past. The example below demonstrates how to
do it (setting expiration time 1 minute ago):

 EXAMPLE
<?php
setcookie("name", "", time()-60);
?>

AUTHENTICATION WITH SESSION CONTROL

We have create login page using php and mysql, we have used mysql_num_rows () for
count the match rows. if rows values is 0 then login is not valid and if rows value is 1
then user is valid. How to implement login and logout code in our project and this
example also use session and session destroy.
EXAMPLE

login.php

<?php
session_start();

if(isset($_GET['msg']))
{
echo $_GET['msg'];
}
if(isset($_POST["submit"]))
{
$con=mysql_connect("localhost","root","");
mysql_select_db("project");

$sql="select * from registration where emailid='".$_POST['txtemail']."' and


password='".md5($_POST['txtpass'])."' and status='a'";
$qsql=mysql_query($sql);

$nsql=mysql_num_rows($qsql);

if($nsql>=1)
{
echo $_SESSION['user']=$_POST['txtemail'];
?>
<script language="javascript">
window.location="logout.php";
</script>
<?php
}
if($nsql <=0)
{ echo "Not Valid user";}}

?>
<html><head></head><body>
logout.php

----------------------

<?php
session_start();

if(isset($_SESSION['user']))
{
unset($_SESSION['user']);
$_SESSION['user']="";
?>
<script language="javascript">
//window.location="login.php?msg=You have logout successfully";
</script>
<?php
}

?>
<a href="login.php?msg=You have logout successfully">logout</a>
2.17 SENDING EMAIL WITH PHP

2.17.2 MAIL()
o PHP must be configured correctly in the php.ini file with the details of how your
system sends email. Open php.ini file available in /etc/ directory and find the
section headed [mail function]
o Windows users should ensure that two directives are supplied. The first is called
SMTP that defines your email server address. The second is called sendmail_from
which defines your own email address.

o The configuration for Windows should look something like this:


[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only


sendmail_from = webmaster@vsc-blog.com

2.17.3 SENDING PLAIN TEXT EMAIL:


 PHP makes use of mail() function to send an email. This function requires
three mandatory arguments that specify the recipient's email address, the
subject of the the message and the actual message additionally there are
other two optional parameters.
mail( to, subject, message, headers, parameters );

 Here is the description for each parameter.

Parameter Description

To Required. Specifies the receiver / receivers of the email

Subject Required. Specifies the subject of the email. This


parameter cannot contain any newline characters

Message Required. Defines the message to be sent. Each line


should be separated with a LF (\n). Lines should not
exceed 70 characters

Headers Optional. Specifies additional headers, like From, Cc,


and Bcc. The additional headers should be separated with
a CRLF (\r\n)

Parameters Optional. Specifies an additional parameter to the


sendmail program

 As soon as the mail function is called PHP will attempt to send the email
then it will return true if successful or false if it is failed.
 Multiple recipients can be specified as the first argument to the mail()
function in a comma separated list.
 Following example will send an HTML email message to
pradeep.vanparia@gmail.com. You can code this program in such a way
that it should receive all content from the user and then it should send an
email.
 EXAMPLE
<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
$to = "pradeep.vanparia@gmail.com";
$subject = "This is subject";
$message = "This is simple text message.";
$header = "From:abc@somedomain.com \r\n";
$retval = mail ($to,$subject,$message,$header);
2.17.4 SENDING HTML EMAIL:

o When you send a text message using PHP then all the content will be treated as
simple text. Even if you will include HTML tags in a text message, it will be
displayed as simple text and HTML tags will not be formatted according to
HTML syntax. But PHP provides option to send an HTML message as actual
HTML message.
o While sending an email message you can specify a Mime version, content type
and character set to send an HTML email.
o Following example will send an HTML email message to
pradeep.vanparia@gmail.com copying it to vanparia.pradeep@gmail.com. You
can code this program in such a way that it should recieve all content from the
user and then it should send an email.
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "pradeep.vanparia@gmail.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:pradeep.vanparia@gmail.com \r\n";
$header = "Cc:vanparia.pradeep@gmail.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
2.17.5 SHORTCOMINGS OF MAIL()
o Email is a short word for electronic mail. You create texts and send them over a
network of computers. The first emails go back to the 1960s. The invention has
influenced our lives and emails have become a popular means of
communication.
o ADVANTAGES
 Emails are easy to use. You can organize your daily correspondence, send
and receive electronic messages and save them on computers.
 Emails are fast. They are delivered at once around the world. No other
form of written communication is as fast as an email.
 The language used in emails is simple and informal.
 When you reply to an email you can attach the original message so that
when you answer the recipient knows what you are talking about. This is
important if you get hundreds of emails a day.
 It is possible to send automated emails with a certain text. In such a way it
is possible to tell the sender that you are on vacation. These emails are
called auto responders.
 Emails do not use paper. They are environment friendly and save a lot of
trees from being cut down.
 Emails can also have pictures in them. You can send birthday cards or
newsletters as emails.
 Products can be advertised with emails. Companies can reach a lot of
people and inform them in a short time.

o DISADVANTAGES
 Emails may carry viruses. These are small programs that harm your
computer system. They can read out your email address book and send
themselves to a number of people around the world.
 Many people send unwanted emails to others. These are called spam
mails. It takes a lot of time to filter out the unwanted emails from those
that are really important.
 Emails cannot really be used for official business documents. They may be
lost and you cannot sign them.
 Your mailbox may get flooded with emails after a certain time so you
have to empty it from time to time.

2.17.6 PHPMAILER
o Sending E-Mail through PHP can be simple, or it can be very complex depending on
what you want to do. A standard plain-text E-Mail is what most developers resort to
because building the MIME headers for HTML mail can be a difficult process. Those
days have been over for quite some time with the amazing PHPMailer library that is
available for free!.
o Whether you host your own separate server or use a third-party service, Simple Mail
Transfer Protocol (SMTP) is the easiest method to have your web server interact with an
email server. Most of the third-party services have their own unique APIs, but they
typically support SMTP. I would recommend using SMTP at least until you find a service
that you love. After that, you might want to integrate with them more tightly through an
API to take advantage of some more advanced features — or you may want to keep using
SMTP to make it easier to switch to a different service in the future.
o To use SMTP in your PHP code, I recommend using PHPMailer. This third-party library
provides the settings and functions you need to send email using a variety of methods,
including SMTP. You can find an SMTP example in the test_smtp_basic.php file in the
examples folder of the library.

PHPMAILER FEATURES
o Can send emails with multiple TOs, CCs, BCCs and REPLY-TOs
o Redundant SMTP servers
o Multipart/alternative emails for mail clients that do not read HTML email
o Support for 8bit, base64, binary, and quoted-printable encoding
o Uses the same methods as the very popular AspEmail active server (COM)
component
o SMTP authentication
o Word wrap
o Address reset functions
o HTML email
o Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Imail, Exchange,
Mercury, Courier
o Works on any win32 or *nix platform
o Flexible debugging
o Custom mail headers
o Multiple fs, string, and binary attachments (those from database, string, etc)
o Embedded image support

o First, place the two necessary files on your server:


 class.phpmailer.php
 class.smtp.php

o Then, include the library and instantiate a PHPMailer object:


require_once('path/to/library/class.phpmailer.php');
$mail = new PHPMailer();

o Next, set up the object to use SMTP and configure it to point to the proper server; I’m
using Postmark in this example:
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.postmarkapp.com";
$mail->Port = 26;
$mail->Username = "#@#@#@#@-####-@@@@-#####-@#@#@#@#@#@#";
$mail->Password = "#@#@#@#@-####-@@@@-#####-@#@#@#@#@#@#";

o Finally, set the properties for the particular email you want to send:
$mail->SetFrom('name@yourdomain.com', 'Web App');
$mail->Subject = "A Transactional Email From Web App";
$mail->MsgHTML($body);
$mail->AddAddress($address, $name);

o Once everything is set up the way you want it, you call the object’s Send method. If the
Send method returns true, then everything worked. If it returns false, then there was a
problem.
if($mail->Send())
{
echo "Message sent!";
}
else
{
echo "Mailer Error: " . $mail->ErrorInfo;
2.17.7 SENDING A PASSWORD BY EMAIL

EXAMPLE
<?php
require 'class.phpmailer.php';

$mail
 In = new
phpPHPMailer;
using rand() function we can send auto generate password to user at their
given email id.
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'MANDRILL_USERNAME'; // SMTP username
$mail->Password = 'MANDRILL_APIKEY'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted

$mail->From = 'from@example.com';
$mail->FromName = 'Your From name';
$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient
$mail->AddAddress('ellen@example.com'); // Name is optional
 EXAMPLE
$mail->IsHTML(true); // Set email format to HTML
<html><head><title>Sending Password email using PHP</title>
$mail->Subject = 'Here is the subject';
</head><body>
$mail->Body
<?php = 'This is the HTML message body <strong>in bold!</strong>';
$mail->AltBody $pass=rand(9999);
= 'This is the body in plain text for non-HTML mail clients';
$to = $_POST["txtemail"];
if(!$mail->Send())
$subject {= $_POST["txtnm"];
echo 'Message
$message could not be sent.';
= $_POST["message"]."\n Your Password is:-".rand(1000,9999);
echo 'Mailer Error: ' . $mail->ErrorInfo;
$header = "From:vanparia.pradeep@gmail.com \r\n";
exit; $retval = mail ($to,$subject,$message,$header);
} if( $retval == true )
{
echo 'Message
echohas been sent';
"Message Password sent successfully...";
}
else
{
echo "Message Password could not be sent...";
}
?>

<form method="post">
<table border="1" align="center">
<tr>
2.17.8 SEND ATTACHMENT IN MAIL

 To send an email with mixed content requires to set Content-type header to


multipart/mixed. Then text and attachment sections can be specified within
boundaries.
 A boundary is started with two hyphens followed by a unique number which can
not appear in the message part of the email. A PHP function md5() is used to
create a 32 digit hexadecimal number to create unique number. A final boundary
denoting the email's final section must also end with two hyphens.
 Attached files should be encoded with the base64_encode() function for safer
transmission and are best split into chunks with the chunk_split() function. This
adds \r\n inside the file at regular intervals, normally every 76 characters.
 Following is the example which will send a file /tmp/test.txt as an attachment. you
can code your program to receive an uploaded file and send it.

EXAMPLE

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy