php html css notes

282
1

Upload: tushar-rajput

Post on 14-Apr-2017

126 views

Category:

Education


5 download

TRANSCRIPT

Page 1: PHP HTML CSS  Notes

1

Page 2: PHP HTML CSS  Notes

2

HTML

HTML is a not a scripting language or programming language.It is a simple markup language with the pair of markup tags.

The first tag is known as opening tag (or) starting tag. The second tag is known as closing (or) end tag.

HTML is used to describe the web pages.

HTML can be written in notepad, notepad++, dream viewer, adov and cs5.

HTML file can be saved with .html as its extension.

The look end of an web page should be same on the all browsers. If it is not same the cross browser compatibility.

Tags in html :

Heading tags are h1, h2,h3,h4,h5,h6

Ex: - <h1>welcome to html</h1>

.

.

<h6> welcome to html</h6>

<hr>: - this tag is used for horizontal line

<br>: - this tag is used for break

<p>: - this tag is used for paragraph content

<b>: - this tag is used for bold content

<i>: - this tag is used for italic content

<link>: - this tag is used for connect the style sheets

<script>: - this tag is used for JavaScript

<big>: - this tag is used for big content

Page 3: PHP HTML CSS  Notes

3

<strong>: - this tag is used for strong content

<blink>: - this tag is used for blink content

<del>: - this tag is used for delete the content

<strike>: - this tag is used for strike

<u>: - this tag is used for underline content

<ins>: - this tag is used for insert content

<q>: - this tag is used for quotation content

<sup>: - this tag is used for super content

Ex: - (a+b) <sup> 2</sup>

<sub>: - this tag is used for subscript content

Entities :

Entities are used to describe the symbols (or) special characters on to the web page. We have certain symbols are not available on the keyboard. So such symbols can be inserting through entities. We have mainly two types of entities they are

1. Named Entity

2. Number Entity

1. Named Entity :

Syntax: - Ampersand + entity name + semicolon

Ex: -&dollar;

2. Number Entity :

Syntax: Ampersand + hash + ascci value+ semicolon

Ex : &#65; =>A

&#153; =>Trademark: tm

Page 4: PHP HTML CSS  Notes

4

List Tags :

List tags are two types

1. Order list : Grouping of elements in the form of order wise through number, upper alpha (A),lower alpha (a), upper roman, lower roman is known as order list

Ex: - Order list.html

<ol type='a' start='25'>

<li>Nokia</li>

<li>Mototola</li>

<li>Sony</li>

</html>

2. Unorder list : Grouping of elements in the form of disk, square circle are known as unorder list

Ex: -

<ul type='square'>

<li>PHP</li>

<li>HTML</li>

</ul>

Definition list : This is used to maintain the heading the description on to the <dl> tag.

Definition term : Definition term creates the heading

Definition description : Which holds the description of the content.

Dt and dd tags are both child tags of DL.

Ex :

<dl>

<dt>Terms & Conditions</dt>

Page 5: PHP HTML CSS  Notes

5

<dd><small><small>some large text matter write here </small></small></dd>

</dl>

Meta tag :

Meta tag is used to generate the traffic on to your web page. Meta tags can be embed into the head tag using Meta tag.

Meta tag helps in search engine ranking on Google page and PTC(pay to click)

Ex : Meta.html

<html>

<head>

<title>Meta Tags</title>

<meta name='keyword' content='PHP,HTML,JQUERY,CSS,HYDERABAD,Institute,Ameerpet'/>

<meta name='description' content='We been in lamp for more than 8years and trained many student ... many have got jobs in PHP ...'/>

<meta http-equiv='refresh' content='5;url=http://www.axis-bank.com'/>

</head>

<body>

<h2>We have changed our Website Name from UTI Bank to AXIS Bank ... Sorry for incontinent Please wait for 5 sec it would be Automatically be Redirected</h2>

</body>

</html>

Page 6: PHP HTML CSS  Notes

6

Link tags :

Links are used to navigate from one page to another page using inter (or) external links.

The attributes we can pass are

Target = “-blank” // new web page

Target = “-new” // new web page

Target = “-self” // open on same page

Links can target to mails and also search the link on same page.

Ex : linktag.html

<html>

<head>

<title>Link Tags</title>

</head>

<body>

<h3>Links Navigation</h3>

<a href='http://www.google.com' target="_blank">Google page</a> ||

<a href='http://www.facebook.com' target='_self'>Facebook Page</a> ||

<a href='Tags.html' target="_new"> Tags Content</a>

</body>

</html>

Image tags:

Images can be embed into the body tag using image tag. Images have extension of jpg, png, gif etc.,

Page 7: PHP HTML CSS  Notes

7

Placing one image on to the web page can be done by two types they are

1.Absolute Path

2.Relative Path

1. Absolute path : Working from the working directory you can call the image from anywhere with respect to its parent directory (or) out of the parent directory (or) external files.

Ex :

<h2>absolute path</h2>

<img src = ‘http://www.google.com/images/mountain.jpg’ alt = ‘beautiful’ border = ‘10’ width = ‘200px’ height = ‘180px;/>

2. Relative path : Using relative path you can work with images on to the same current working directory (or) sub folders did not out of your parent directory.

Ex :

<h2>relation tags</h2>

<img src="suresh.jpg" width='140px' height='150px' border='0' title='suresh'/><br>

<img src="../water lilies.jpg" width='200px' height='180px' border='3' title='suresh'/><br>

<img src="../../sunset.jpg" width='200px' height='180px' border='3' title='suresh'/><br>

<img src="new folder/dsc_0083.jpg" width='200px' height='180px' border='3' title='suresh'/><hr>

Tables create :

Tables are used to put down content in tabular structure. Table tag can be embed into your body tag using

Page 8: PHP HTML CSS  Notes

8

<table>

<tr> table row</tr>

<td> table data (or) content</td>

</table>

The general attributes that we can pass in table tag are

Border = “<num>”Width = “<num>”Height = “<num>”Cellpadding = “<num>”Cellspacing = “<num>”Align= left/center/rightBackground = “image path”Fames = “box/group/lhs/rhs/above/below/vsides/hsidesRules = all/middle/bottomColspan =“<num>”Rowspan = “<num>”Bgcolor = “color name”

Ex :

<body>

<table border = “1” align = “center” width = “70%”>

<tr><td>employee detailsl</td></tr>

<table>

<tr><td>s.no</td><td>Name</td><td>designation</td></tr>

<tr><td>1</td><td>suresh</td><td>php programmer</td></tr>

</body>

Cell padding : Cell padding is used to maintain the distance between its content and from its wall (or) border

Page 9: PHP HTML CSS  Notes

9

Cell spacing : Cell spacing is used to increase the wall (or) the border

Frame set :

We can divide the body into number of divisions that are passed as an argument based on rows (or) columns working with frame set you should ensure that body tag is not given

Note : Frame set is a depreciated tag and would be working with future versions

Ex :

<frameset cols='30%,25%,*'>

<frame src = 'links.html' scrolling='no' >

<frame src = 'entities.html' >

<frame src = 'list.html' >

</frameset>

Iframes :

Ex :

<body>

<p align='center'><a href='list.html' target='x'>List Page</a> | <a href='links.html' target='x'>Links Page</a><br><br>

<iframe src='list.html' name='x' width='600px' height='200px' ></iframe></p>

</body>

Page 10: PHP HTML CSS  Notes

10

Page 11: PHP HTML CSS  Notes

11

Cascading Style Sheets(CSS)

Css stands for cascading style sheet. Css is used to put some styles (or) colors on to the web page. Css can be embed into the html head tag using style tag. There are mainly 3 different flavors to attach this style on to the web page. Which are mainly

1. Internal style sheet

2. External style sheet

3. In-line style sheet

1. Internal style sheet :

An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this:

<head><style type="text/css">hr {color:sienna;}p {margin-left:20px;}body {background-image:url("images/back40.gif");}</style></head>

2. External style sheet :

An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section:

<head><link rel="stylesheet" type="text/css" href="mystyle.css" /></head>

Page 12: PHP HTML CSS  Notes

12

An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with .css extension. An example of a style sheet file is shown below:

hr {color:sienna;}p {margin-left:20px;}body {background-image:url("images/back40.gif");}

3. In-line style sheet :

An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly!

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph:

<p style="color:sienna;margin-left:20px">This is a paragraph.</p>

We have one more style which is given by default by browsers which is not editable

External style sheet can be saved with .css as its extension

Syntax :

(Attributes) element (or) class (or) id {property: value ;}

CSS Syntax :

A CSS rule has two main parts: a selector, and one or more declarations:

The selector is normally the HTML element you want to style.

Each declaration consists of a property and a value.

Page 13: PHP HTML CSS  Notes

13

The property is the style attribute you want to change. Each property has a value.

Selector : Selectors are identifiers which give styles based on elements, class (denoted by period ‘.’), id (denoted by ‘#’).We have 7 kinds of selectors.They are :

Element selector Class selector Class with element selector Id selector Id with element selector Attribute selector Pseudo selector

1.Element selector :

Ex : element.html

<html>

<head>

<title>Element Selector</title>

<style>

h1{color:green;}

</style>

</head>

<body>

<h1>Welcome to my Website</h1>

</body>

</html>

Page 14: PHP HTML CSS  Notes

14

2.Class selector :

The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.

This allows you to set a particular style for many HTML elements with the same class.

The class selector uses the HTML class attribute, and is defined with " . (dot)"

In the example below, all HTML elements with class="center" will be center-aligned:

3.Class with Element Selector :

Example for Class Selector and Class with Element Selector

Ex : class-selector.html

<html>

<head>

<title>Class with Element Selector</title>

<style>

h1{color:green;} //element selector

.x{color:red;} // class selector

//.x{font-family:impact;}

p.x{font-size:20pt;color:black;} // Class with element selector

</style>

</head>

<body>

<h1>Welcome to my Website</h1>

Page 15: PHP HTML CSS  Notes

15

<h1 class='x'>This is new Website </h1>

<h1>hello This is my next line</h1>

<p class='x'>Hello my next page</p>

<p>Rajesh</p>

</body>

</html>

4.Id selector :

The id selector is used to specify a style for a single, unique element.

The id selector uses the id attribute of the HTML element, and is defined with a "#".

The style rule below will be applied to the element with id="para1":

5.Id with Element Selector :

Example for Id Selector & Id with Element Selector

Ex : Id-selector.html

<html>

<head>

<title>Id with Element Selector</title>

<style>

h1{color:green;} //element selector

.x{color:red;} // class selector

//.x{font-family:impact;}

p.x{font-size:20pt;color:black;} // Class with element selector

#g{background:green;} //id selector

p#g{text-transform:uppercase;} //id with element selector

Page 16: PHP HTML CSS  Notes

16

</style>

</head>

<body>

<h1>Welcome to my Website</h1>

<h1 class='x'>This is new Website </h1>

<h1>hello This is my next line</h1>

<p class='x'>Hello my next page</p>

<p class='x' id='g'>Rajesh</p>

<h2 class='x' id='g'>Amith</h2>

<h2 class='x' id='g'>David</h3>

<p class='x' id='g'>Praveen</p>

<p class='x' id='g'>Karthik</p>

</body>

</html>

6.Attribute selector :

Ex : attribute.html

<html>

<head>

<title>Attribute Selector</title>

<style>

.x{

color:deeppink;

font-family:impact;

}

Page 17: PHP HTML CSS  Notes

17

input[type='text']{

color:deeppink;

}

</style>

</head>

<body>

Name : <input type='text’ name='name' class='x'><br>

username : <input type='text' name='uname'><br>

</body>

</html>

7.Pseudo selector :

Ex : pseudo.html

<html>

<head>

<title>Pseudo Selector</title>

<style>

p:first-letter{

font-size:30pt;

color:deeppink;

font-family:arial black;

}

p:first-line{

color:orange;

}

Page 18: PHP HTML CSS  Notes

18

</style>

</head>

<body>

<p>This is my first email to all you guys his is my first email to all you guys his is my first email to all you guys his is my first email to all you guys his is my first email to all you guys</p>

</body>

</html>

Css cheat sheet :

Font-styles :

font-style : italic,normal

font-variant : small-caps,narmal,small,caps(capital letters)

font-weight : normal,lighter,bold, bolder, number(100->light, 900->bolder)

font-size : <num> px;

font-family : family of font

Text properties :

1. letter-spacing : <num>px

2. word-spacing : <num>px

3. line-height : <num>px

4. text-align : left/center/right/justify ->order from left (or) right

5. text- decoration : name, blink,underline,overline,line-through

6. text-transform : capitalize(upper case/lower case(everything convert))

7.text-indent : <num>px (distance from line to first letter)

Page 19: PHP HTML CSS  Notes

19

The text-align property is used to set the horizontal alignment of a text. Text can be centered, or aligned to the left or right, or justified. When text-align is set to "justify", each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers).

The text-decoration property is used to set or remove decorations from text. The text-decoration property is mostly used to remove underlines from links for design purposes:

The text-transform property is used to specify uppercase and lowercase letters in a text.It can be used to turn everything into uppercase or lowercase letters, or capitalize the first letter of each word.

The text-indent property is used to specify the indentation of the first line of a text.

Background property :

CSS background properties are used to define the background effects of an element.

background-color : ‘color name’;

background-image : url(image path name);

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

The background image for a page can be set like this:

background-repeat : no-repeat,reapt-x,reapt-y,repeat(*);

By default, the background-image property repeats an image both horizontally and vertically.

Some images should be repeated only horizontally or vertically, or they will look strange, like this: 

background-attachment : fixed,scroll;

Page 20: PHP HTML CSS  Notes

20

background-position :{x,y}left,center,right,bottom,top

When using a background image, use an image that does not disturb the text.

Showing the image only once is specified by the background-repeat property:

//background : order wise

List properties :

list-style-type : none,disk,circle,square,decimal,upper-alpha,lower-alpha,upper-roman,lower-roman;

list-style-position : outside (*) / inside;

list-style-image:url(image path name);

Box properties :

Padding : inside element

Margin auto = center

Overflow = visible (*), hidden, auto, scroll

Ex :

<html>

<head>

<title>BOX properties</title>

<style>

//body{margin:0px;}

p{text-align:center;}

.z{

background:#ccc;

padding:15px;

Page 21: PHP HTML CSS  Notes

21

width:50%;

height:80px;

margin:auto;

overflow:auto;

text-align:justify;

}

</style>

</head>

<body>

<p>

<input type='checkbox' name='t&c' />Terms & Conditions

<p class='z'>

Some large text matter</p>

</p>

</body>

</html>

Border Properties :

border-width : <num>px;

border-style : solid,groove,inset,outset,double,dotted,dashed;

border-color : <color name>

//border: order wise

Div tag :

Div tag stands for division tag.Div tag is the block level element. A block level element creates a block with coming left and right breaks in it.

Page 22: PHP HTML CSS  Notes

22

Ex : div tag, p tag, h1 to h6, table tag, ul and li tags

In-line element : These particular elements will take the content span only and does not have breaks init

Span tag is the natural tag.

Ex :

<html>

<head>

<title>in-line element</title>

<style>

h1 {

background : green; display : inline;

}

b{

Background: gold;

}

a.{text-align : center; background : yellow; display : block;

}

</style>

</head>

<body>

<h1>hello</h1><b>hello</b><i>hello</i><p>hello</p> <hr>

<span class = ‘a’>hello</span>

<div class = ‘a’>hello</div> <hr>

<h3> converting block & inline & respectively<h3>

<h1> hello</h1>

Page 23: PHP HTML CSS  Notes

23

</bold>

</html>

Display properties :

Visibility : we have visible (or) hidden

Display : none, in-line, block;

Padding : <num>px all sides

Padding : top left

0px 0px

Bottom right

Margin : <num> all sides

Margin : top right bottom left

0px 0px 0px 0px

Templates :

Position properties : Position in css we have absolute, relative and fixed position

Relative position : Working from the current position we can move the element anywhere on to the web page but cannot be moved on the top of the position place.

Absolute & fixed position : Placing from the current position we can move the element to all corner of the web page and also one top of the position place .once an element declare as fixed (or) absolute this will turn to in-line element and this will also carry ‘7’ index init

Ex : position.html

<html>

<head>

<title>Position properties</title>

Page 24: PHP HTML CSS  Notes

24

<style>

div{background:blue;color:#fff;font-size:17pt; font-weight:bold;padding:10px;margin:4px;}

.r{background:gold;color:#000;position:relative;left:30px;top:120px;}

.a{background:blue;position:absolute;top:50px;left:6px;}

.f{background:deeppink;color:#000;position:fixed;bottom:0px;right:0px;}

</style>

</head>

<body>

<div>Normal Position</div>

<div class='a'>Absolute Position</div>

<div class='r'>Relative Position</div>

<div class='f'>Fixed Position</div>

<h1>some large text matter </h1>

<h1> some large text matter </h1>

<h1> some large text matter </h1>

<h1> some large text matter </h1>

</body>

</html>

Page 25: PHP HTML CSS  Notes

25

Page 26: PHP HTML CSS  Notes

26

JavaScript

JavaScript is client side scripting language. JavaScript is the case sensitive. JavaScript can be used for AJAX integration and validation. JavaScript can be embed into the head tag and body tag using

script tag. JavaScript can be saved with .js as its extension.

Content:

VariablesDatatypesOperators (Assignment, Arthamatic, Post/Pre [Inc/Dec],

Comparission, Relational, Conditional, Logical,Ternary)Alert,prompt,confirm Built in Functions (Arrays,Date,Math,String)DOM (Document Object Module)Navigator,images,screen,location,historyDocument – (getElementById, getElementsByTagName,

getElementsByName)

Events : General Events (onclick(), ondblclick(), onload(),

onunload(), onreset(), onsubmit(), onfocus(), onblur(), onchange())

Mouse Events (onmouseover(), onmousemove(), onmousedown(), onmouseout() )

Key Board Events – (onkeyup() , onkeydown() )

Document. write () :

document.write is the printing method in javascript.Which is output statement to the browser.

Ex: first.html

<html>

<head>

Page 27: PHP HTML CSS  Notes

27

<script src='ext.js' type='text/javascript' language='javascript'></script>

<script>

document.write('This is Called from Head Tag<br>');

</script>

</head>

<body>

<h1>Welcome</h1>

<script>

document.write('This is Called from Body Tag<br>');

</script>

</body>

</html>

ext.js:-

document.write('<h1>This is called from External Page</h1>');

Variables :

Variables are case sensitive. Declaring a variable in JavaScript as variable name = value;

Variables are "containers" for storing information.

Ex : var a = 10; var = default

The correct method to declare are :

Var a = 10;

Var_a = 10;

Var first-name = ‘suresh’;

Page 28: PHP HTML CSS  Notes

28

Var firstName = ‘suresh’;

Var $name = ‘suresh’;

Wrong method :

Var #name = ‘suresh’;

Var 1a = 10;

Var first name = ‘suresh’;

Data Types :

String :

Collection of characters inside a single (or) double quotations are known as string ,working with single quotation and adding double quotation in it is valid.But adding single quotation inside a single quotation is not valid.

Ex : datatypes.html

<html>

<head>

<script>

var a = 10;

document.write('<h1>'+a);

document.write(' - ');

document.write(typeof(a));

document.write('<br>');

var f = 10.25;

document.write(f);

document.write(' - ');

document.write(typeof(f));

Page 29: PHP HTML CSS  Notes

29

document.write('<br>');

firstname = 'Rajesh';

document.write(firstname+' - '+typeof(firstname)+'<br>');

firstname = firstname+' Kumar';

document.write(firstname+' - '+typeof(firstname)+'<br>');

firstname += 'B';

document.write(firstname+' - '+typeof(firstname)+'<br>');

document.write('<hr>String Methods<hr>');

document.write('i\'ll Pay the Bill Tomorrow');

</script>

</head>

<body>

<h1>Welcome</h1>

</body>

</html>

Operators :

1.Assignment operator: ‘ = ‘ is used to assign values.

The assignment operator ‘=’ is used to assign values to JavaScript variables.

Ex :

<script>

document.write('<h1 align="center">Assignment Operator</h1>');

var x = 10;

Page 30: PHP HTML CSS  Notes

30

document.write("The Value is : "+x);

</script>

2.Arithmetic operator: -

The arithmetic operator ‘ +’ is used to add values together. Arithmetic operators are used to perform arithmetic between variables and/or values.

Ex :

<script>

document.write('<h1 align="center">Arthamatic Operator</h1>');

a = 5; b = 3;

document.write("Addition : "+(a+b)+'<br>');

document.write("Multiplication : "+(a*b)+'<br>');

document.write("Division : "+(a/b)+'<br>');

document.write("Minus : "+(a-b)+'<br>');

document.write("Modulus : "+(a%b)+'<br>');

</script>

3.Comparision operator :

Comparision operators are used in logical statements to determine equality or difference between variables or values.

Ex :

<script>

Document.write('<h1 align="center">comparision Operator</h1>');

if(10 != '10'){

Page 31: PHP HTML CSS  Notes

31

document.write('<h2>Correct</h2>');

} else {

document.write('<h2>Not Correct</h2>');

}

document.write('<h1 align="center">Post & Pre Increment</h1>');

m = 10;

n = (m++)+(++m)+(m++)+(++m);

document.write('The Value of m is : '+m+'<br>The Value of n is : '+n+'<br>');

</script>

4.Relational operator : < , > , <= , >=

5.Logical operator : &&(and) -- ||(or)

6.Ternary operator :

Syntax for Ternary Operator :

Var a= 10;

Type = (a%2 == 0)? ‘even number’: ‘odd number’;

//document.write(“the value you entered is : ”+type);

document.write(type);

Conditions :

1.If else :

Whenever a condition is ‘if’ it is true that part of the constructor will be excuted.if condition is fail ‘else’ part would get executed.

Page 32: PHP HTML CSS  Notes

32

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

use this statement to execute some code if the condition is true and another code if the condition is false

Syntax :

If (cond)

{

//code

}

else

{

// code

};

2.If else if :

if else if (or) ladder condition will take more than one condition (or) multiple conditions. If all the conditions fail in if else if constructor then only else part get executed

Use this statement to select one of many blocks of code to be executed

Syntax :

If(cond)

{

//code

}

Page 33: PHP HTML CSS  Notes

33

else if (cond)

{

//code

}

else if (cond)

{

//code

}

.

.

else

{

//default value;

}

3.Switch :

Use the case in-order wise. This is main concept in switch case

Use this statement to select one of many blocks of code to be executed

Conditional statements are used to perform different actions based on different conditions.

Syntax : switch(n) { case 1: execute code block 1

Page 34: PHP HTML CSS  Notes

34

  break; case 2: execute code block 2  break; default:   code to be executed if n is different from case 1 and 2 }

Looping methods :

While: do-while:

Syntax: Syntax:

Initialize method Initialize

While (cond) do

{ {

//code //code

} }

1.While :

Working with while loops it will first check the initialize part and checks the condition. If condition is true it will get into the constructor and takes place until condition fail and comes out of the constructor.

loops through a block of code while a specified condition is true

Page 35: PHP HTML CSS  Notes

35

2.Do-while :

This will also checks the initialized part .but for only first time it will get into the constructor and execute the code and checks the conditions later and if condition is true looping takes place (or) else it come out of the constructor with at least single time execution code

3.For-loop :

For loop first initialize condition an inc/dec will be done on same (single) line for the every first time it will initialize with part them check within condition if condition is true the constructor will get excuted.condition fail will come out of the for loop (constructor)

Loops execute a block of code a specified number of times, or while a specified condition is true.

Syntax :

For (initialize; condition; inc/dec )

{

//code

}

Arrays :

A variable which can hold more than one value is none as array (or) super variable as array can be defined is JavaScript as

Var a = new Array (values); // a->super variable

To find the length of the array we can go with length = array name.length;

If the array index is been initialize more than the current index++ then memory is wasted in JavaScript

In arrays initializing string index the printing method will not work in JavaScript

Note : - document.write() (or) looping method will not able to print string indexes

Page 36: PHP HTML CSS  Notes

36

While, do-while , for-loop will not print string indexes in JavaScript so to print string indexes we can go withSyntax: - for (var name in Array name)

For is key word in JavaScript which will print the string index

The Array object is used to store multiple values in a single variable.

An array is a special variable, which can hold more than one value, at a time.

Create an Array :

An array can be defined in three ways.

The following code creates an Array object called myCars:

1: var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab";       // argument to control array's size)myCars[1]="Volvo";myCars[2]="BMW";

2: var myCars=new Array("Saab","Volvo","BMW"); // condensed array

3: var myCars=["Saab","Volvo","BMW"]; // literal array

Ex : Array.html

<script>

var a = new Array(10,20,30,40);

document.write('The Array is : '+a+'<br>');

document.write('Length of Array : '+a.length+'<br>');

document.write('Index at 2 : '+a[2]+'<br>');

a[2] = a[2]*2;

document.write('The Array is : '+a+'<br>');

Page 37: PHP HTML CSS  Notes

37

a[4] = 'New Value';

document.write('The Array is : '+a+'<br>');

var b = new Array();

b[0] = 100;

b[1] = 200;

b[2] = 300;

b[3] = 400;

b['Name'] = 'Rajesh';

b['Age'] = 30;

b[7] = 700;

b[10] = 1000;

document.write('<hr>Single string Index : '+b['Name']+'<hr>');

document.write('The Array is : '+b+'<br>');

for(i=0;i<b.length;i++){

document.write('Index at : '+i+' = '+b[i]+'<br>');

}

document.write('<hr>');

for(c in b){

document.write(c+' = '+b[c]+'<br>');

}

document.write('<hr>');

var d = [10,20,30];

document.write('The Array in d is : '+d+'<br>');

document.write('The Array in d is : '+d.length+'<br>');

Page 38: PHP HTML CSS  Notes

38

document.write('<hr>');

var e = {'Name':'Rajesh','Age':30,10:20,'Status':'Active'};

document.write('The Array in d is : '+e+'<br>');

for(i=0;i<e.length;i++){

document.write('Index at : '+i+' = '+e[i]+'<br>');

}

for(c in e){

document.write(c+' = '+e[c]+'<br>');

}

</script>

Double dimensional array:

An array can have more than one array is called double dimensional array.

Ex : douledimensionarray.html

<html>

<head>

<script>

var a = [[1,'Ajay',[45,62,49,72,55,84]],[2,'Rajesh',[48,62,94,72,38,62]],[3,'Suresh',[48,63,82,97,45,28]]];

//document.write(a[1][1]);

document.write('Name is : '+a[2][1]);

document.write("<table border='1' align='center' width='60%' >");

document.write("<tr><th colspan='9'>Student Marks Memo Report </th> ");

Page 39: PHP HTML CSS  Notes

39

document.write("<tr><td rowspan='2'>Roll No</td> <td rowspan='2'>Name</td><td colspan='6' align='center'>Subjects</td><td rowspan='2'>Pass/Fail</td></tr>");

document.write("<tr><td>English</td><td>Hindi</td><td>Telugu </td> <td>Maths</td><td>Science</td><td>Social</td></tr>");

document.write("<tr><td>"+a[0][0]+"</td></tr>");

</script>

</head>

<body>

<tr><td><script>document.write(a[1][0]);</script></td><td><script>document.write(a[1][1]);</script></td></tr>

</table>

</body>

</html>

Array built-in Functions :

Join : Join is the pre-defined key-word in the JavaScript .which will convert the given array into the separator passed default separator is coma (,).

Concat : concat is joining more than array in single array is called concat.

Reverse : reverse in JavaScript the array last being is first. First is last without (descending order) the original array will also get affected. If we use reverse function.

Sort : sort is nothing but given the order is ascending order .

Unshift : unshift will add the value at the starting of the array. The variable use for unshift will holds the length of the array and the original array would get affected.

Page 40: PHP HTML CSS  Notes

40

Shift : shift function will not hold any arguments should will remove the starting value of the array.The variable unshift will hold the removed value.

Push : push is nothing but insert the value into the array at the end of array is called push.

Pop : pop is nothing but remove the last value in the array is called the pop.

Ex : arraybuiltin.html

<script>

var a = new Array('This','is','my','new','car');

document.write('The Original Array is : '+a+'<br>');

b = a.join(' ');

document.write('Join Method : '+b+'<br>');

var a = new Array(10,20,30);

var b = new Array(40,50);

var c = new Array(60,70,80);

document.write("Concat Two Arrays : "+a.concat(b)+"<br>");

document.write("Concat All Given Array : "+a.concat(b.concat(c))+" <br>");

var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');

b = a.reverse();

document.write("Reverse of an Array : "+b+'<br>');

document.write("Original Array : "+a+'<br>');

var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');

b = a.sort();

document.write("Assending Order : "+b+'<br>');

Page 41: PHP HTML CSS  Notes

41

document.write("Original Array : "+a+'<br>');

b = a.reverse();

document.write("Reverse With Desending Order : "+b+'<br>');

document.write("Original Array : "+a+'<br>');

var x = new Array(10,20,30);

b = x.unshift(5);

document.write("Unshift Method : "+x+'<br>');

document.write("The Value Stored in B : "+b+'<br>');

var x = new Array(5,10,20,30);

b = x.shift();

document.write("shift Method : "+x+'<br>');

document.write("Removed Value is stored B : "+b+'<br>');

var x = new Array(5,10,20,30);

b = x.push(40);

document.write("Push last Value to Array Method : "+x+'<br>');

document.write("B holds the length of the Array: "+b+'<br>');

var x = new Array(5,10,20,30);

b = x.pop();

document.write("Pop Removes last Value in Array : "+x+'<br>');

document.write("B holds the Removed Value: "+b+'<br>');

</script>

Functions:-

Functions in javascript are case sensitive once declare a function name and try to re-declare. The same function name will overwrite previous function name. Functions are used to debug the code and

Page 42: PHP HTML CSS  Notes

42

analize the errors easily. Working with length of the code will be reduced.

We have mainly 4 types of the functions in JavaScript that is

1. Function without arguments and return value

2. Function with arguments and no return value

3. Function with return value and no arguments

4. Function with arguments and return value

Syntax :

Function function name (arguments, arg)

{

//code

}

1. Function without arguments and return value

Ex :

<script>

test();

function test(){

document.write('This is Function without Aurgument<br>');

document.write('This is my function Content<br>');

}

function test1(){

document.write('Overwritten is done on the previous printing methods<br>');

}

test();

Page 43: PHP HTML CSS  Notes

43

test();

</script>

<body>

<script>

test();

</script>

</body>

2. Function with arguments and no return value

Ex :

<style>

.error{background:gold;color:green;padding:10px;margin:auto;width:60%;font-size:18pt;}

.success{background:black;color:#fff;padding:10px;margin:auto;width:60%;font-size:18pt;}

</style>

<script>

function welcome(name){

document.write("Welcome ! "+name+'<br>');

}

welcome('Rajesh');

welcome('Amith');

function statement(type,message){

document.write("<div class='"+type+"'>"+message+"</div>");

}

//statement("error","Welcome Guest ! ");

Page 44: PHP HTML CSS  Notes

44

statement("success","Welcome Rajesh");

</script>

3. Function with return value and no arguments

Ex :

<script>

function test(){

document.write('This is line 01<br>');

document.write('This is line 01<br>');

return 10 2;

document.write('This is line 01<br>');

document.write('This is line 01<br>');

}

test();

var x = test();

document.write('The Value in x is : '+x+'<br>');

</script>

4. Function with arguments and return value

Ex :

<script>

function square(num){

return num*num;

}

document.write('The Square root of 5 is : '+square(5)+'<br>');

document.write('The Square root of 5 is : '+square(square(5))+'<br>');

Page 45: PHP HTML CSS  Notes

45

</script>

Math built-in function :

In JavaScript we have mainly seven kinds of math objects which are pre-defined and can be called respective key-words. Which are included in JavaScript library.

Ex : math.html

<script>

function r(txt){

document.write('<h2>'+txt+'</h2>')

}

r("<u>Javascript Predefined Math Constant Object </u>");

r('Eulers Constant : '+Math.E);

r('Pi Value : '+Math.PI);

r('SQRT OF 2 : '+Math.SQRT2);

r('Natural Log 2: '+Math.LN2);

r('Natural Log 10 : '+Math.LN10);

r('Log base 2 of Eulers : '+Math.LOG2E);

r('Log base 10 of Eulers : '+Math.LOG10E);

r("<u>Javascript User - defined Math Object </u>");

r('Max Value : '+Math.max(10,20,30));

r('Min Value : '+Math.min(10,20,30));

r('Sqrt Value : '+Math.sqrt(25));

r('2 pow 4 : '+Math.pow(2,4));

r('Absolute Value : '+Math.abs(-9));

Page 46: PHP HTML CSS  Notes

46

r('Ceil Value : '+Math.ceil(2.11111));

r('floor Value : '+Math.floor(2.9999));

r('round Value : '+Math.round(2.5111111));

r('Random Number : '+Math.random());

r('Number Between 1 to 1000 : '+Math.round(Math.random()*1000));

</script>

String built-in functions :

Ex : stringbuilt.html

<script>

function r(txt){

document.write(txt+'<br>');

}

var str = "lamp Institute";

r('String Value = '+str);

r("Length of the String = "+str.length);

r("Color of String = "+str.fontcolor('green'));

r('Upper Case = '+str.toUpperCase());

r('Lower Case = '+str.toLowerCase());

r('Big Font = '+str.big());

r('Bold Font = '+str.bold());

r('Small Font = '+str.small());

r('Italic Font = '+str.italics());

r('Superscript = '+str.sup());

r('sub script = '+str.sub());

Page 47: PHP HTML CSS  Notes

47

r('<hr><h2><u>Slice Function([begin, stop]) </u></h2>');

r('Slice(4) = '+str.slice(4));

r('Slice(4,8) = '+str.slice(4,8));

r('Slice(-9) = '+str.slice(-9));

r('Slice(-9,8) = '+str.slice(-9,8));

r('Slice(-9,-3) = '+str.slice(-9,-3));

r('<hr><h2><u>Substring Function([From, to]) </u></h2>');

r('substring(4) = '+str.substring(4));

r('substring(4,8) = '+str.substring(4,8));

r('substring(4,2) = '+str.substring(4,2));

//r('substring(-9) = '+str.substring(-9));

r('<hr><h2><u>substr([start, length]) </u></h2>');

r('substr(4) = '+str.substr(4));

r('substr(5,8) = '+str.substr(5,8));

r('substr(-9) = '+str.substr(-9));

r('substr(-9,2) = '+str.substr(-9,1));

r('CharAt(0) = '+str.charAt(1));

r('charCodeAt(1) = '+str.charCodeAt(1)); //ascill Value of Index

mob = 'Z123456789';

r('charCodeAt = '+mob.charCodeAt(0));

r('Indexof = '+str.indexOf('T'));//-1

r('lastIndexof = '+str.lastIndexOf('t'));

r('indexOf = '+str.indexOf('t',9));

r('Search = '+str.search('z'));//-1

Page 48: PHP HTML CSS  Notes

48

r('Match = '+str.match('z'));//null

</script>

Mobile function :

Ex : mob.html

<script>

function r(txt){

document.write(txt+'<br>');

}

mob = "8855644045";

r(isValidMobile(mob));

function isValidMobile(val){

if(val.length != 10){

return "Please Enter 10-Digit Mobile Number";

}

f = val.charAt(0);

if(f == '7' || f == '8' || f == '9'){

} else {

return 'Please Check the First Digit of Number & try Again';

}

return isNumeric(val);

}

function isNumeric(val){

for(i=0;i<val.length;i++){

Page 49: PHP HTML CSS  Notes

49

ascii = val.charCodeAt(i);

if(ascii < 48 || ascii >57){

return 'Only Numbers Allowed Please Check again';

}

}

return 'Valid Mobile Number';

}

</script>

Date functions: -

Date function can be defined with variable is equal to new date. This function is pre-defined in JavaScript which will explain the system timing (or) running the domain it will capture the running domain.

Get time () : This is unique time constant which is created find generate number of milliseconds right from night jan 1st 1970.

Ex : date.html

<script>

function r(txt){

document.write(txt+'<br>');

}

var d = new Date();

r('The value in d is : '+d);

r('Unix Time Constant that is Midnight Jan 01,1970 (no of millseconds : ) '+d.getTime());

r('Date : '+d.getDate());

r('Day : '+d.getDay());

Page 50: PHP HTML CSS  Notes

50

r('Month : '+(d.getMonth()+1));// 0 -11

r('Year : '+d.getYear());//works only in ie...

r('FullYear : '+d.getFullYear());

r('Hours : '+d.getHours());

r('Minutes : '+d.getMinutes());

r('Seconds : '+d.getSeconds());

r('Time is : '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());

</script>

DOM :

DOM contains these layers

1.IMAGES

2.LOCATIONS

3.SCREEN------------------> Get Element ById

4.DOCUMENTS-----------> GetElementByTagName

5.NAVIGATOR------------ > GetElementByName

6.EMBED

Ex : dom.html

<script>

function dochange(){

document.testForm.fname.value = alert("Please Enter");

document.testForm.fname.value = 'Enter Name';

document.testForm.lname.style.border="2px solid red";

document.testForm.lname.style.width="200px";

}

Page 51: PHP HTML CSS  Notes

51

</script>

<body>

<form name='testForm'>

First Name : <input type='text' name='fname' /><br>

Last Name : <input type='text' name='lname'/><br>

<input type='button' name='change' value='DoChange' onclick="javascript:dochange();"/>

</form>

</body>

Get Element ById :

This particular function will match the id of the element and that particular matching function will get executed

Ex : getElementById.html

<script>

function dochange(){

var x = document.getElementById('test').value;

document.getElementById('test').value = x.toUpperCase();

document.getElementById('test').style.color = 'red';

}

</script>

<body>

<form name='testForm'>

First Name : <input type='text' name='fname' id='test' onblur="dochange();"/><br>

First Name : <input type='text' name='lname' id='fldtest' onkeyup="dochange();"/>

Page 52: PHP HTML CSS  Notes

52

</form>

</body>

GetElementByTagName :

This particular function will match tag name and excute the function which we are passing as a tag name

Ex : getElementsByTagName.html

<script>

function dochange(){

var a = document.getElementsByTagName('div');

for(i=0;i<a.length;i++){

a[i].style.width = '400px';

a[i].style.background = '#ddd';

a[i].style.border = '4px dotted green';

}

}

</script>

<body onmouseover='dochange();'>

<h1>Welcome to My Web Page</h1>

<p>This is my First Page</p>

<p>This is my First Page</p>

<p>This is my First Page</p>

<p>This is my First Page</p>

<div>What is Social Hub</div>

</body>

Page 53: PHP HTML CSS  Notes

53

GetElementByName :

This particular function will match element name and that part of the function will get excutes.

Ex : getElementsByName.html

<script>

function dochange(){

var a = document.getElementsByName('x');

for(i=0;i<a.length;i++){

a[i].style.width = '400px';

a[i].style.background = '#ddd';

a[i].style.border = '4px dotted green';

}

}

</script>

<body onmouseover='dochange();'>

<h1>Welcome to My Web Page</h1>

<p>This is my First Page</p>

<p>This is my First Page</p>

<p>This is my First Page</p>

<p>This is my First Page</p>

<div>What is Social Hub</div>

</body>

Note 1 : As ids are unique we have singular matching so we can getElementById as singular.

Page 54: PHP HTML CSS  Notes

54

Note 2 : GetElementByTagName & ByName works the array format and these are plural.

Events :

Whenever an event is trigger and then that particular matching function will excuted.

a)innerHTML : innerHTML is used to push the dynamic values on to the HTML page.

b)set Interval : setInterval is pre-defined key-word in JavaScript which takes 2 arguments the first argument can be expression (or) function the second argument can be number of milliseconds.

c)Alert : Alert gives you a single button option until it is click It will allowed you to navigate on the server.

Ex : alert.html

<script>

alert("Please Agree with Our Terms & condition");

</script>

<body>

Welcome

</body>

d)Confirm : Confirm is used two options until something is being click. It won’t allowed to navigate the server and if it is click based on the values it will moved to the respect pages.

Ex : confirm.html

<script>

var x = confirm("Are You legally 18+ then enter to site");

if(x == true){

document.write("Welcome to my Terrorist Site");

Page 55: PHP HTML CSS  Notes

55

} else {

document.write("Thank You for leaving Please <a href='http://www.google.com'>Click Here</a>");

}

</script>

<body>

</body>

e)Eval : Eval is pre-defined function in JavaScript which will evaluate the given function in between the JavaScript (function)

f)parseINT : This is pre-defined function in JavaScript which will convert the floating value into integer value.

g)parseFLOOT : This is pre-defined function in JavaScript which will convert the integer value into floating value.

Ex : innerHTML & set Interval time.html

<script>

function r(txt){

document.write(txt+'<br>');

}

function currTime(){

var d = new Date();

var time = timeFormat(d.getHours())+':'+timeFormat(d.getMinutes())+':'+timeFormat(d.getSeconds());

return 'Present Time : '+time;

}

function timeFormat(val){

return ((val<10)?'0':'')+val;

Page 56: PHP HTML CSS  Notes

56

}

function writeTime(id){

return document.getElementById(id).innerHTML = currTime();

}

</script>

<body>

<div id='currentTime' align='right'>

<script>

r(currTime());

setInterval("writeTime('currentTime')",1000);

</script>

</div>

</body>

Page 57: PHP HTML CSS  Notes

57

Page 58: PHP HTML CSS  Notes

58

PHP Rasmus Lerdorf is the founder of the PHP in 1995. PHP is the server side scripting language. Php needs a server to excute the file. Php files should be saved with .php as its extension ".php3", or

".phtml" Or else our server will not excute unknown extension apart from

.html, .cpi, .cgs, Php supports all the data bases that are present in the market

Ex:-mySql,mssql,infonix,Sybase,ibmdb2,postgresql………etc Php can be worked on all the operating systems that is

windows,linux,max,solaries…etc Php can communicate with different servers

Ex:-SMTP(Simple mail transfer protocal), imap (internet max access protocal), LDAP, Informix, Oracle, Sybase, Solid, PostgreSQL

PHP can be install as a software tags we get many of the server filesEx : Xampp, Wamp, easy php, mamp

PHP stands for PHP: Hypertext Preprocessor PHP is an open source software PHP is free to download and use PHP is easy to learn and runs efficiently on the server side

Xampp : Xampp stands for

x------------------------>platform(windows,linux,mac,solaries)

a------------------------->apache(web server)

m------------------------>mysql(database file)

p------------------------->perl(perl scripting in php)

p------------------------->php/my admin (web database tool)

php current version is 5.3.8

Page 59: PHP HTML CSS  Notes

59

Wamp : Wamp stands for

w------------------------>window exv

a------------------------>apache(web server)

m------------------------>mysql(database file)

p------------------------>php/my admin (web database tool)

Mamp : Mamp stands for

m------------------------>mac ‘os’

a------------------------->apache(web server)

m------------------------>mysql(database file)

p------------------------->php/my admin (web database tool)

Apache contain the 1-65535 ports.In that 1-1024 are pre-reserved ports.

Tmp : Tmp holds session details & temp upload files.

Htdocs : After installing xampp we have to store our files into the folder called htdocs. Once files are saved in htdocs we can open with the location path as

http://localhost/abc(folder name)/first.php

Echo : echo is the output method in php.

Basic PHP Syntax :

<?php

echo “universal way of writing php<br>”;

?>

<script language = ‘php’>

Page 60: PHP HTML CSS  Notes

60

echo “javascript way of writtting php<br>”;

</script>

<?

echo”short tag way of writing php<br>”;

?>

<%

1echo “asp way of writing php<br>”;

%>

Comments in PHP :

In PHP, we use // to make a one-line comment or

/* and */ to make a comment block

<html><body>

<?php//This is a comment

/*This isa commentblock*/?></body></html>

Page 61: PHP HTML CSS  Notes

61

Printing methods in php :

a.Echo : echo is an argument can print multiple arguments. Echo as a function can print only one argument.

b.Print : print is an argument can print only one argument.print also a function

Ex: - print”arg<br>”;

c.Printf : printf will take formatting string with respected values as print

Ex : printf(“(int%d) (float%f) (string %s) (asci%c)”);

d.Print-r : print-r will print array of string

Ex: - $g = array (10,20,30,true,’kalam’);

Print-r($g);

e.Var-dump : It is also printing method which is used debugging the errors very easily. This not used in production level (live environmental )

Ex : var-dump($g);

<h1>Printing Methods in PHP</h1>

<?php

$a = 10; $b = 20; $c = 30;

echo "Arg01","Arg02","Arg03<br>";

echo $a,$b,$c,'<br>';

echo ("Arg01<hr>");

print "Arg01<br>";

print("Arg01<hr>");

Page 62: PHP HTML CSS  Notes

62

printf("(int %d) (float%.2f) (string %s) (Ascii %c) ",22.25,10.2545,'Rajesh',97);

echo '<hr>';

$g = array(10,20,30,true,'Rajesh');

print_r($g);

echo '<hr>';

var_dump($g);

?>

Controlling :

Ex : controlling.php

<style>

b{color:green;}

</style>

<?php

echo "line 01<br>";

echo "line 02<br>";

echo "line 03<br>";

?>

<b>This is Bold Tag</b><hr>

<?php

if(false){

echo "<b>The 1<sup>st</sup> is Executed<br></b>";

} else {

echo "<b>The 2<sup>nd</sup> is Executed<br></b>";

Page 63: PHP HTML CSS  Notes

63

}

?>

<hr>

<h2>Alternate Method</h2>

<?php

if(true){

?>

<b>The 1<sup>st</sup> is Executed<br></b>

<?php

}

else

{

?>

<b> The 2<sup>nd</sup> is Executed<br></b>

<?php

}

?>

Variables :

Variables are "containers" for storing information. Variables in PHP starts with a $ sign, followed by the name of

the variable. The variable name must begin with a letter or the underscore

character. A variable name can only contain alpha-numeric characters and

underscores (A-z, 0-9, and _). A variable name should not contain spaces.

Page 64: PHP HTML CSS  Notes

64

Variable names are case sensitive (y and Y are two different variables).

Ex : variables.php

<h1>Variables in php</h1>

<?php

$a = 10;

$name = 'Rajesh';

$_name

$_name

$n123

$_1232

$1_name

$first_Name

echo 'The Value is : ',$a.'<br>';

echo 'The Name is : ',$name,'<br>';

?>

<script>

var a = 15;

document.write('The Value of a is : '+a+'<br>');

</script>

In PHP, a variable does not need to be declared before adding a value to it.

Page 65: PHP HTML CSS  Notes

65

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.

PHP has four different variable

local global static Super global array variable

Local variable : A variable declared within a PHP function is local and can only be accessed within that function.

Ex : localvariable.php

<?php

function test(){

$a = 10;

echo 'The Value of $a inside function is : ',$a,'<br>';

}

test();

echo 'The Value of $a Outside Function is : ',$a,'<br>';

?>

Static variable : When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable not to be deleted.

To do this, use the static keyword when you first declare the variable.

Page 66: PHP HTML CSS  Notes

66

Ex : staticvariable.php

<?php

function test(){

$a = 10;

static $b = 20;

echo 'The Value of $a inside function is : ',$a,'<br>';

echo 'The Value of $a inside function is : ',$b,'<br>';

$a++;

$b++;

}

echo 'The Value of $b outside is : ',$z,'<br>';

test();

test();

?>

Global variable : Global scope refers to any variable that is defined outside of any function.

Global variables can be accessed from any part of the script that is not inside a function.

To access a global variable from within a function, use the global keyword:

Ex : global.php

<?php

$x = 10;

Page 67: PHP HTML CSS  Notes

67

echo 'The Value of $x = ',$x,'<br>';

function test(){

//global $x;

echo 'The Value of $x inside Function = ',$x,'<br>';

echo '$GLOBALS["x"] = ',$GLOBALS['x'],'<br>';

}

test();

?>

Super global array variable : ‘$ global’ is the super global array variable. This is the pre-defined keyword. In php we have mainly some of the super global variables. This can be used with their keywords.

i) $_EVN : This is used for getting the information of your operating system ($_ENV (PATH))

ii) $_SERVER : This will give you the information about your server(apache information)

iii) $_GET : It is used for form processing through get method (or) query string

iv) $_POST : This is used for form processing through post method in secure manner

v) $_REQUEST : It will send the form through both get and post and cookie

vi)$_COOKIE : This is used to get the information about the browser who is using the web(computer)

vii)$_SESSION : It is used to get the information of the user in between login and logout details are store at server machine.

Page 68: PHP HTML CSS  Notes

68

Operators :

1. Assignment operator: = is used to assign values to variables in PHP

2. Arithmetic operator: +,-,/,*,%

3. Increment & decrement operator: i++,++I & i--, --i

4. Comparison operator: ==,!= ,===

5. Relational operator: <=, >=, <>

6. Logical operator: &&, ||, and, or

7. Error handling operator :

8. Scope resolution & this operator : ::----->scope, &------->this

Ex : operator.php

<?php

echo '<h1 align="center">Assignment Operator</h1>';

$a = 10;

echo 'The Value is : '.$a.'<br>';

echo 'The Value is Added by 2 : ',$a += 2,'<br>';

$name = 'Rajesh';

echo 'My name is : '.$name,'<br>';

$name .= ' Kumar';

$name = $name.' Kumar';

Page 69: PHP HTML CSS  Notes

69

echo 'My name is : ',$name,'<br>';

echo '<h1 align="center">Arthamatic Operator</h1>';

echo 'The value of 2+3 : ',2+3,'<br>';

echo 'The Value of 2-3 : ',2-3,'<br>';

echo 'The Value of 2/3 : ',2/3,'<br>';

echo 'The Value of 2*3 : ',2*3,'<br>';

echo 'The Value of 2%3 : ',2%3,'<br>';

echo '<h1 align="center">Increment & Decrement [INC/DEC]</h1>';

echo '<h2>POST & PRE increment</h2>';

$x = 10;

echo 'The Value of $x = ',$x,'<br>';

echo 'The Value of $x++ = ',$x++,'<br>';

echo 'The Value of $x = ',$x,'<br>';

echo 'The Value of ++$x = ',++$x,'<br>';

echo 'The Value of $x = ',$x,'<br>';

echo '<h2>POST & PRE Decrement</h2>';

echo 'The Value of $x-- = ',$x--,'<br>';

echo 'The Value of $x = ',$x,'<br>';

echo 'The Value of --$x = ',--$x,'<br>';

echo 'The Value of $x = ',$x,'<br>';

echo '<h1 align="center">Comparision Operator</h1>';

Page 70: PHP HTML CSS  Notes

70

var_dump(10 == 10);echo'<br>';

var_dump(10 != '10');echo'<br>';

echo '<h1 align="center">Relational Operator</h1>';

var_dump(10<=10);echo '<br>';

var_dump(10<>'10');echo '<br>';//not Equal to

echo '<h1 align="center">logical Operator</h1>';

var_dump(true && true);echo '<br>';

var_dump(true && false);echo '<br>';

var_dump(true || true);echo '<br>';

var_dump(true || false);echo '<br>';

var_dump(false AND FALSE);echo '<br>';

var_dump(false OR FALSE);echo '<br>';

echo '<h1 align="center">Error Handling Operator</h1>';

echo @sqrt();

//@test();

echo 'Some Data';

echo '<h1 align="center">Scope Resolution & this Operator {:: & ->(this)}</h1>';

class A{

static $z = 100;

public $a = 20;

public $k = 50;

Page 71: PHP HTML CSS  Notes

71

protected $b = 30;

private $c = 40;

function test(){

echo "A Test Function called inside Class A";

}

}

$obj = new A;

echo $obj->a,'<br>';

echo $obj->k,'<br>';

//echo $obj->b,'<br>';

//echo $obj->c,'<br>';

echo ' The Static Value is : ',A::$z,'<br>';

echo 'The Function inside Class is : ',$obj->test(),'<br>';

?>

Type Casting: -

Conversion of the one data type into another data type is known as type casting. in php we have mainly two types of costing

1. Temporary type casting

2. Permanent type casting

1. Temporary type casting : Casting which can be done for single step by pre-defined the data type keyword. That particular variable will hold Temporary type casting.

Page 72: PHP HTML CSS  Notes

72

Ex : temporary.php

<?php

$x = "10.254Kgs";

var_dump($x);echo "<br>";

var_dump((int)$x); echo "<br>";

var_dump($x); echo '<br>';

var_dump((float)$x); echo '<br>';

var_dump((boolean)$x);echo'<br>';

var_dump((string)$x);echo "<br>";

var_dump($x);echo "<br>";

var_dump(floatval($x)); echo '<br>';

var_dump(intval($x)); echo '<br>';

var_dump($x);echo "<br>";

?>

2. Permanent type casting : This can be done by using pre-defined key-word set type.which hold two arguments

Syntax : set type (var name,’int’);

Ex : Permanent type casting.php

<?php

echo '<h1>Permanent Type Casting</h1>';

$x = "10.254Kgs";

Page 73: PHP HTML CSS  Notes

73

settype($x,'float');

var_dump($x);echo "<br>";

settype($x,'int');

var_dump($x);echo "<br>";

settype($x,'boolean');

var_dump($x);echo "<br>";

settype($x,'int');

var_dump($x);echo "<br>";

var_dump($x);echo "<br>";

settype($x,'float');

var_dump($x);echo "<br>";

?>

Type juggling : conversion of data types by using expression to another data types are known as type juggling.

Ex : typejuggling.php

<?php

echo 'true + true : ',true+true,'<br>';

if(null){

echo "Printed";

} else {

echo "Not Printed";

Page 74: PHP HTML CSS  Notes

74

}

?>

Variable validation function :

i) Isset : Isset of variables will check with the variable initialize or not and return Boolean

ii) empty(var name) : empty function will check the variable whether it is null or not and return Boolean

iii) Unset (var name) : This function will remove the variable (or) delete the variable

iv) get type(var name) : This function will let us know the argument data type in the form of string ,this should be used because the coming variable would be depreciated.

Ex : variable_validation.php

<?php

$x = 10;

var_dump($x);echo '<br>';

var_dump(isset($x));

var_dump(isset($a));echo '<hr>';

$z = '';

var_dump(empty($z));

var_dump(empty($y));

$k = 10;echo '<br>';

var_dump(gettype($k));

Page 75: PHP HTML CSS  Notes

75

unset($x);

var_dump(isset($x));

?>

Data Types :

Php supports mainly 8 kinds of data types among which four are stable data types, two are compound data types and another two are special data types

a)Stable data types :

i) int (or) integer

ii) Float (or) real (or) decimal

iii) Boolean data types

iv) string data types

i)int (or) integer : All non decimal values . range in between 2(32-1) to -2(32-1)

Ex :

<?php

echo "<h1 align='center'>Stable Data types</h1>";

echo "<h2>Integer Data Type</h2>";

$x = 10;

var_dump($x);echo '<br>';

$x = (pow(2,32-1)-1);

var_dump($x); echo '<br>';

Page 76: PHP HTML CSS  Notes

76

$judge = 2147483647;

var_dump($judge);

?>

ii) Float (or) real (or) decimal : All decimal values. Range in between 10(38) to 10(-38)

Ex :

<?php

echo "<h2>Float Data Type</h2>";

$a = 10.25;

var_dump($a);echo '<br>';

?>

iii) Boolean data types : Boolean data types return the values in the form of true (or) false

Ex :

<?php

echo "<h2>Boolean Data Type</h2>";

$a = false;

var_dump($a);

?>

iv) String data types : Collection of characters enclose in between single (or) double cotations are known as string data types.

Page 77: PHP HTML CSS  Notes

77

Ex :

<?php

echo "<h2>String Data Type</h2>";

$x = 10;

echo '<br>The Value of $x is ',$x,'<br>';

echo "The Value of $x is :$x";

$name = "Rajesh";

echo '<br>my name is $name <br>';

echo "my name is $name <br>";

$x = 10;

$y = 20;

echo 'The value of $x+$y = ',$x+$y,'<br>';

echo "The value of $x+$y = ",$x+$y,'<br>';

?>

b)Compound data types :

Compound data types again two types

1. Array data type

2. Object data type

1. Array data type : Array data type which can hold more than one value. In php we have mainly 3 kinds of arrays

i) Numerical array

ii) Associative array

Page 78: PHP HTML CSS  Notes

78

iii) Mixed array

Declaring an array in php can be done by two types

array as the function array as a square bracket

i) Numerical array :

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

There are two methods to create a numeric array.

In the following example the index are automatically assigned (the index starts at 0):

$cars=array("Saab","Volvo","BMW","Toyota");

In the following example we assign the index manually:

$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";

Ex :

<?php$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";?>

ii) Associative array :

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

Page 79: PHP HTML CSS  Notes

79

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.

Example 1

In this example we use an array to assign ages to the different persons:

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example 2

This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";

The ID keys can be used in a script:

<?php$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";?>

The code above will output:

Peter is 32 years old.

iii) Mixed array :

Mixed array is nothing but combination of numerical & associative array is known as mixed array.

Page 80: PHP HTML CSS  Notes

80

Ex : mixedarrays.php

<?php

$a = array("Name"=>"Rajesh","Age"=>30);

print_r($a);

echo '<hr>';

echo '<h1 align="center">Mixed Arrays</h1>';

define('A','ABC');

define('B','XYZ');

$c = 10;

$d = 20;

$g = array(0=>10,1=>20,'Name'=>'Raj','Age'=>30,5=>500,5.55=>600,-9=>'Negative value',true=>200,false=>200,''=>'Empty Value',NULL=>'Null Value',A=>B,$c=>$d);

echo '<pre>';

print_r($g);

echo '</pre>';

?>

2. Object data type :

Object is an instance of class.Class can be denoted with in class name. Collection of variables and functions are known as class.For Calling class we should create an object then that particular variable is known as object variable.

Page 81: PHP HTML CSS  Notes

81

Ex :

<?php

echo "<h2>Object Data Type</h2>";

class A{

public $x = 10;

public $a = 20;

function test(){

echo 'A test Function called<br>';

}

}

$b = new A;

var_dump($b);

echo '<br>Public Value $x = ',$b->x,$b->test(),'<br>';

?>

Special data types :

Special data types are again two types

i) Resource data types

ii) Null data types

i) Resource data types : Resource data type is calling an external variable value into another variable using (&) resource variable.

Page 82: PHP HTML CSS  Notes

82

ii) Null data types : This is the pre-defined key-word. When a variable not initialize and by asking through printing method. This will result in null value.

Ex :

<?php

echo "<h1 align='center'>Special Data types</h1>";

echo "<h2>Reference Data Type</h2>";

$x = 10;

$y = $x;

echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';

$x = 12;

echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';

$y = 'Rajesh';

echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<hr>';

echo "<h2>Resourse Data Type</h2>";

$a = 10;

$b = &$a;

echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';

$a = 'Raj';

echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';

$b = 'Amith';

echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';

Page 83: PHP HTML CSS  Notes

83

echo "<h2>Null Data Type</h2>";

var_dump($z);

?>

Constant :

Define : Define is the pre-defined key-word in php. This will take two arguments. The first argument being the constant identifier which identifier its second argument value. We can pass third argument as Boolean to make case in-sensitive

Ex : constant.php

<?php

define('x',10,true);

echo x,'<br>';

echo X;

echo '<hr>';

define('url','http://www.socialhub.com',true);

echo uRl,'/register.php';

echo '<hr>';

define('SITE_NAME','http://www.socialhub.in-hyderabad','Social Hub');

?>

<h1>About us</h1>

we at <?php echo SITE_NAME;?> are in training ........

<h1>Contact Us</h1>

Page 84: PHP HTML CSS  Notes

84

<?php echo SITE_NAME;?>

street ......

<h1>FAQ</h1>

what we do at <?php echo SITE_NAME;

?>

Conditions :

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

a)If condition :

IN PHP IN PERL

If (cond) if (cond) :

{ //code

//code else if (code) :

} //code

else if (cond) else (cond) :

{ //code

//code end else if ;

}

Page 85: PHP HTML CSS  Notes

85

else (cond)

{

//code

}

b)Switch condition :

Syntax :

switch (cond) : switch (cond):

{ |

Case1 : |

//code |

Break; |

Case2:

//code |

Break; end switch;

|

|

Default:

//code

}

Page 86: PHP HTML CSS  Notes

86

Ex :

<html><body><?php$x=1;switch ($x){case 1:  echo "Number 1";  break;case 2:  echo "Number 2";  break;case 3:  echo "Number 3";  break;default:  echo "No number between 1 and 3";}?></body></html>

c)While condition : The while loop executes a block of code while a condition is true

Syntax:

While (cond) while (cond):

{ //code inc/dec

//const code inc/dec endwhile

Page 87: PHP HTML CSS  Notes

87

}

Ex:

<html><body><?php$i=1;while($i<=5)  {  echo "The number is " . $i . "<br />";  $i++;  }?></body></html>

d)Do-while condition : The do-while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.

Syntax :

Do do:

{ //code Inc/dec

//code enddo while(cond);

}

While (cond)

Example :

The example below defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5:

Page 88: PHP HTML CSS  Notes

88

<html><body><?php$i=1;do  {  $i++;  echo "The number is " . $i . "<br />";  }while ($i<=5);?></body></html>

e)For loop : Loops execute a block of code a specified number of times, or while a specified condition is true. The for loop is used when you know in advance how many times the script should run.

Syntax :

For(initialize;cond;inc/dec)

//code

end for

Example :

The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html><body><?phpfor ($i=1; $i<=5; $i++)  {  echo "The number is " . $i . "<br />";  }?>

Page 89: PHP HTML CSS  Notes

89

</body></html>

f)for each : for each is usefull for all non-sequence data of an array. Associative array ,numerical array object data of an array.

The general syntax is

foreach (arrayName as arr[value]))

{

echo arr [value];

}

Another syntax is

foreach (arrayname as key=>value)

{

echo key’-‘value (or) echo “key-value”;

}

Ex : foreach.php

<?php

$a = array("Name"=>"Rajesh","Age"=>30);

/*foreach(arrayname as value){

echo arr[value];

}*/

foreach($a as $v){

echo $v,'<br>';

}echo '<hr>';

/*foreach(arrayname as key=>value){

echo key,' - ',value;

Page 90: PHP HTML CSS  Notes

90

}*/

foreach($a as $k=>$v){

echo "$k - $v<br>";

//echo $k,' - ',$v,'<br>';

}

?>

Functions : Functions are case in-sensitive.Once function can be declare con’t be re-declare in the program.

The real power of PHP comes from its functions.

In PHP, there are more than 700 built-in functions.

To keep the script from being executed when the page loads, you can put it into a function.

A function will be executed by a call to the function.

You may call a function from anywhere within a page.

Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a

number)

Syntax:

function function name (arg)

{

//code

Return value

}

Page 91: PHP HTML CSS  Notes

91

There are mainly 8 kinds of functions in php

1. Conditional Function : A function which is enclose inside condition is considered as conditional function

Ex : conditional.php

<?php

if(false){

function test(){

echo "I am a Conditional Function <br>";

}

}

@test();

2. Variable Function : When a function name is told In variable. Variable can be used for excuting the function in a place of function name

Ex : variables.php

?php

function test(){

echo "I am a Variable Function <br>";

}

test();

$a = 'test';

echo $a;echo '<br>';

$a();

$a();

Page 92: PHP HTML CSS  Notes

92

3. Function Function : Function is define inside another function is called as function-function.

Ex : function's function.php

<?php

Function parent f(){

echo “iam write the function function<br>”;

If(!function_exists(childF))

{

function child F()

{

echo “I need some one to open parent file for me to excute<br>”;

}

}

}

Parent F();

Child F();

Parent F()’

?>

4. Function with arguments : Function can be defined with one (or) more arguments. If arguments are not passed then it creates warning in the program

Ex :

<?php

function test($x,$y){

echo 'The Value of $x = ',$x,'<br>';

Page 93: PHP HTML CSS  Notes

93

echo 'The Value of $y = ',$y,'<br>';

}

test('Raj','Kiran');

test(10,20);

test('Amith');

test();

?>

5. default argument : A function at the time of a declaration if argument are assign with some values they will be treated as optional (or) default argument value and they can be passed with value (or) can left without passing the value. Works at the side default argument must be passing last in the program at the argument list

Ex :

<?php

function test($x=10,$y=20){

echo 'The Value of $x = ',$x,'<br>';

echo 'The Value of $y = ',$y,'<br>';

}

test(100,200);

test('Raj','Kiran');

test();

?>

6. Overloaded argument : A function can be define with argument (or) that the defined arguments they are still acknowledge inside the function using various pre-defined function

Page 94: PHP HTML CSS  Notes

94

i) func_num_args() : return the total number of arguments which are passed in the function

ii) func_get_args() : return the array with all the arguments with the function

iii) func_get_args(position) : return the argument value at the specified position

Ex :

<?php

function test(){

echo "<h1>Overloaded Concept</h1>";

echo 'The Overloaded Length = ',func_num_args(),'<br>';

print_r(func_get_args());

echo '<hr>';

for($i=0;$i<func_num_args();$i++){

echo 'Index at : ',$i,' - ',func_get_arg($i),'<br>';

}

echo '<hr><h1>For Each Method</h1>';

$y = func_get_args();

foreach($y as $k=>$v){

echo "$k => $v<br>";

}

}

test(10,20,'Rajesh');

7. Function with Return value : Return key-word can be stop the execution of the function.Return key-word can optionally followed with a value which is return variable.Whenever a function is valid

Page 95: PHP HTML CSS  Notes

95

another one value con’t be passed after the return statement multiple value con’t be club as array (or) object and con’t be return wherever a function is called.

Ex :

<?php

function test(){

echo "This is Return Information<br>";

//return 10;

echo "I am second info<br>";

return = 82;

echo "I am second info<br>";

}

test();

$y = test();

echo $y;

//echo $y;

8. i) arguments passed by value : When an argument passed by value any change for the value inside the function owned be reflected in the variable outside the function

ii) Arguments passed by reference : When an argument passed by resource and change for the inside with be refer to the variable outside the function

Ex :

<?php

function test($x,&$y){

$x +=2;

Page 96: PHP HTML CSS  Notes

96

$y +=10; // $y = $y+10;

echo 'The Value of $x = ',$x,'<br>';

echo 'The Value of $y = ',$y,'<br>';

}

$a = 5;

$b = 10;

echo '$a = ',$a,'<br>';//5

echo '$b = ',$b,'<br>';//10

test($a,$b);

echo '$a = ',$a,'<br>';//5

echo '$b = ',$b,'<br>';//10

?>

Built-in Functions : a)Math Functions :

Ex :

<?php

echo 'Math Pi Value = ',M_PI,'<br>';

echo 'Math Pi Value = ',M_PI_2,'<br>';

echo 'Math Pi Value = ',M_PI_4,'<br>';

echo 'Eulers Constant = ',M_E,'<br>';

echo 'SQRT 2 = ',M_SQRT2,'<br>';

echo 'SQRT 2 = ',M_SQRT1_2,'<br>';

echo 'Log of 2 = ',log(2),'<br>';

echo 'Log base 10 of 2 = ',log10(2),'<br>';

Page 97: PHP HTML CSS  Notes

97

echo 'Absolute Value = ',abs(-9),'<br>';

echo 'Exponent of 1 = ',exp(2),'<br>';

echo 'pi() = ',pi(),'<br>';

echo 'ceil value = ',ceil(2.1111),'<br>';

echo 'Floor Value = ',floor(2.9999),'<br>';

echo 'round = ',round(2.51458),'<br>';

echo 'round = ',round(2.51558,2),'<br>';

echo 'rad2deg(M_PI) = ',rad2deg(M_PI),'<br>';

echo 'rad2deg(M_PI) = ',rad2deg(M_PI_2),'<br>';

echo 'rad2deg(M_PI) = ',rad2deg(M_PI_4),'<br>';

echo 'deg2rad = ',deg2rad(180),'<br>';

echo 'sin 90 = ',sin(M_PI_2),'<br>';

echo 'tan 45 = ',tan(M_PI_4),'<br>';

echo 'hypot value = ',hypot(3,4),'<br>';

echo 'rand(min,max) = ',rand(100,1000),'<br>';

echo 'min value = ',min(10,20,30),'<br>';

echo 'max Value = ',max(2.999,2.998),'<br>';

?>

b)Date & Time Functions :

Date : date is the pre-defined constant in php. It will generate current date according to the number of arguments passed.

Mktime : Which can have arguments (hr, min, sec, month, day, year) unique time stamp.

Check date() : Let us known the validate in a year

j----> represents day of the month without leading zeros

Page 98: PHP HTML CSS  Notes

98

l---->view letter represents of the day of the way

L---> whether it’s a leap year (or) not

W---> week number of year weeks starts from Monday

w----> numerical represents of day of the way 0 for Monday through 6 for Saturday

S---> English original safix for the day of the month two character ex: -st ,nd, rd,th

F----> a full representation of the month such as January (or) March

M---> short representation of the month such as jan (or) mar

m---> numerical representation of the month with leading zero’s means 0-12

n---> numerical representation of month without zero’s which is 1-12

d---> number of days given in a month 28 (or) 31

y---> two digits representation of a year

Y---> it is representation of the full year

Time : Number of milliseconds sec right from unique time stamp

a---> lowercase ante meridiem and post meridiem

A---> uppercase ante meridiem and post meridiem

B---> swatch internet time

g---> 12- hours format of an hour without leading zeros

G---> 24- hour format of an hour without leading zeros

h---> 12- hours format of an hour with leading zeros

H--->24- hours format of an hour with leading zeros

i---> minutes with leading zero’s

s---> seconds with leading zero’s

Page 99: PHP HTML CSS  Notes

99

u---> microseconds (added in php 5.2.2)

Ex :

<?php

echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';

date_default_timezone_set('America/Denver');

echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';

echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';

date_default_timezone_set('America/Los_Angeles');

echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';

echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';

date_default_timezone_set('Asia/Calcutta');

echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';

echo 'Today Date : ',@date("M-dS-Y, h:i:s A"),'<br><hr>';

var_dump(checkdate(02,29,1975));

echo '<hr>No of milliseconds from Unix time Constant ',time(),'<br>';

echo '<hr>Feature Date & time <br>';

echo 'Event is on : ',(date("M-dS-Y, h:i:s a",mktime(7,9,52,8,23,2012))),'<br><hr>';

echo date('Y');

?>

c)Array built-in Functions :

<?php

$a = array(10,20,30);

Page 100: PHP HTML CSS  Notes

100

function r($arr,$func=''){

if(!empty($func)){

echo "<h2 align='center'><u>$func</u></h2>";

}

foreach($arr as $k=>$v){

echo "$k = $v<br>";

}

echo '<hr>';

}

echo 'Array count = ',count($a),'<br>';

echo 'Size of = ',sizeof($a),'<br>';

echo 'Sum of Array = ',array_sum($a),'<br>';

echo 'Product of Array = ',array_product($a),'<br>';

$a = array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'[email protected]','Gender'=>'Male');

r($a,'Normal Array');

$b = array_change_key_case($a,CASE_UPPER);

r($b,'Upper Case');

$b = array_change_key_case($a,CASE_LOWER);

r($b,'Lower Case');

$b = array_flip($a);

r($b,'Array Flip');

$b = array_change_key_case(array_flip($a),CASE_UPPER);

r($b,'Array Flip Values');

Page 101: PHP HTML CSS  Notes

101

$a = array('Doctor','Fruit','Software');

$b = array('Patient','Orange','PHP');

r(array_combine($a,$b),'Array Combine');

$a = array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'[email protected]','Gender'=>'Male');

echo '<h2 align="center">Array Chunk</h2>';

$b = array_chunk($a,3);

echo '<pre>';

print_r($b);

echo '</pre>';

$a = array(10,20,30);

$b = array(10,20,40,50);

r(array_merge($a,$b),'Array Merge');

r(array_intersect($a,$b),'Array Intersect');

r(array_diff($a,$b),'Array Diff');

$a = array('[email protected]','[email protected]','[email protected]','[email protected]','[email protected]');

r(array_unique($a),'Array Unique');

r(array_reverse($a),'Array Reverse');

$a = array(10,20,30);

array_unshift($a,5);

r($a,'Unshift Method');

array_shift($a);

r($a,'shift Method');

Page 102: PHP HTML CSS  Notes

102

array_push($a,40);

r($a,'Push Method');

array_pop($a);

r($a,'Pop Method');

$ns = $ss = $as = $ks = array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'[email protected]','Gender'=>'Male');

r($ns,'Normal Array');

sort($ss);

r($ss,'Sorted Array');

rsort($ss);

r($ss,'Reverse Sort Array');

asort($as);

r($as,'Associative Sort Array');

arsort($as);

r($as,'Associative Reverse Sort Array');

ksort($ks);

r($ks,'Key Sort Method');

krsort($ks);

r($ks,'Key Sort Reverse Method');

echo "<h2 align='center'>array_key_exists , array_search , in_array</h2>";

$a = array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'[email protected]','Gender'=>'Male');

echo 'Do i have Email Feild : ',var_dump(array_key_exists('Gender',$a)),'<br>';

Page 103: PHP HTML CSS  Notes

103

echo 'Do we have Value with some : ',var_dump(array_search(30,$a)),'<br>';

echo 'Do we have Value with some : ',var_dump(in_array('Male',$a)),'<br>';

$a = array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'[email protected]','Gender'=>'Male');

r(array_keys($a),'Array Keys Calling');

r(array_values($a),'Array Value Calling');

$str = 'Hey i am from India & my name is Praveen';

$b = explode(" ",$str);

//print_r($b);echo '<br>';

echo 'The Length of your total Words = ',count($b),'<br><hr>';

for($i=0;$i<count($b);$i++){

echo 'The index at ',$i,' = ',$b[$i],'<br>';

}

$a = array('[email protected]','[email protected]','[email protected]','[email protected]','[email protected]','[email protected]','[email protected]','[email protected]');

print_r($a);

$b = implode(',',$a);

<br><br>

To : <input type='text' name='name' value='<?php echo $b;?>' size='60'/>

<hr>

<?php

Page 104: PHP HTML CSS  Notes

104

$a = array('born','child','teen','father','dead');

r($a,'Normal Array');

echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';

echo 'Next : ',next($a),'<br>';

echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';

echo 'Previous location : ',prev($a),'<br>';

echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';

echo 'End Value : ',end($a),'<br>';

echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';

echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<br>';

echo 'Reset ',reset($a),'<br>';

echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at ',key($a),'<hr>';

$a = array('Name'=>'Rajesh','Age'=>30);

r(Each($a),'Each Method');

r(Each($a),'Each Method');

$a = array('ram','processor','computer');

list($gb,$intel,$dell) = $a;

echo "$gb & $intel together makes $dell faster<br><hr>";

$str = "write some large text matter.";

echo $str,'<br><hr>';

echo '<h2>Wordwrap</h2>';

Page 105: PHP HTML CSS  Notes

105

echo wordwrap($str,20,'<br>',true);

?>

d)String built-in Functions :

<?php

echo '<h2>';

$str = "lamp institute";

echo "Normal String = ",$str,'<br>';

echo "Length of String = ",strlen($str),'<br>';

echo "To Upper Case = ",strtoUpper($str),'<br>';

echo "To Lower Case = ",strtoLower($str),'<br>';

echo "Upper case First Word = ",ucfirst($str),'<br>';

echo "Upper case words = ",ucwords($str),'<br>';

echo 'Reverse = ',strrev($str),'<br>';

echo '<hr>';

echo 'Position of str = ',strpos($str,'t'),'<br>';

echo 'last Position of str = ',strrpos($str,'t'),'<br>';

echo 'Postion of str after t again = ',strpos($str,'t',9),'<br>';

echo 'Position insensitive = ',stripos($str,'lamp'),'<br>';

echo 'last position at t insensitive = ',strripos($str,'T'),'<br>';

echo 'strstr will extract the entire string : ',strstr($str,"In"),'<br>';

echo 'strstr will extract the entire string : ',stristr($str,"in"),'<br>';

$name = 'Rajesh Kumar';

echo "substr = ",substr($name,0),'<br>';

echo "substr = ",substr($name,7,4),'<br>';

Page 106: PHP HTML CSS  Notes

106

echo "substr = ",substr($name,-5,-1),'<br>';

$url = 'http://www.google.com?status=active';

$url .= '&';

echo 'substr = ',substr($url,0,-1),'<br>';

echo 'replace = ',str_ireplace('lamp','Apache',$str),'<br>';

$a = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

echo str_shuffle($a),'<hr>';

echo substr(str_shuffle($a),0,12);

echo '<hr>';

$name = "O'henry";

echo $name,'<br>';

echo addslashes($name),'<br>';

echo stripslashes('O\'henry'),'<br>';

echo strip_tags("<b><i>Hi i am not feeling well</i></b>");

echo '<hr>';echo '<h2>';

$pwd = 'computer';

echo 'Original Name : ',$pwd,'<br>';

echo '<h1 align="center">One Way Encrypt</h1>';

echo 'Encrypt with MD5 = ',md5($pwd),'<br>';//32 char value

echo 'Encrypt with MD5 strict = ',md5($pwd,true),'<br>';//16 bit binary format

echo 'Encrypt with sha1 = ',sha1($pwd),'<br>';//40 char vlaue

echo 'Encrypt with sha1 strict= ',sha1($pwd,true),'<br>';//20 binary vlaue

Page 107: PHP HTML CSS  Notes

107

echo 'Crypt = ',crypt($pwd),'<br>';

echo 'crypt salt = ',crypt($pwd,'d4'),'<br>';

echo '<h1 align="center">Encrypt & Decrypt Method</h1>';

echo 'encrypt = ',base64_encode($pwd),'<br>';

echo 'decrypt = ',base64_decode('Y29tcHV0ZXI='),'<br>';

echo '<h1 align="center">Url Encode & Decode</h1>';

$url = 'http://www.lamp.com?status=success&id=7&pid=20';

echo 'Original url = ',$url,'<br>';

echo 'encode = ',urlencode($url),'<br>';

echo 'decode = ',urldecode('http%3A%2F%2Fwww.lamp.com%3Fstatus%3Dsuccess%26id%3D7%26pid%3D20'),'<br><hr>';

echo '<pre>';

$name = " Rajesh ";

echo 'My name is :',$name,'<br>';

echo 'My name is :',rtrim($name),'<br>';

echo 'My name is :',ltrim($name),'<br>';

echo 'My name is :',trim($name),'<br>';

echo '</pre>';

?>

PATH :

FILE : The full path and filename of the file. If used inside an include, always contains an absolute path with some links

LINE : The current line number of the file.

DIR : The directory of the file.

Realpath : Returns absolute pathname

Page 108: PHP HTML CSS  Notes

108

Basename : Returns filename component of path

Ex :

<?php

echo "File Information : ",__FILE__,'<br>';

echo "Base Name : ",basename(__FILE__),'<br>';

echo "Directory Name : ",dirname(__FILE__),'<br>';

echo "Directory Name : ",__dir__,'<br>';

echo "real Path : ",realpath(__FILE__),'<br>';

//echo "real Path : ",realpath('../..'),'<br>';

echo "Line NO : ",__LINE__,'<br>';

echo '<hr>';

$a = pathinfo(__FILE__);

//print_r($a);

foreach($a as $k=>$v){

echo $k,' = ',$v,'<br>';

}

?>

e)File Functions :

1) stat(file path) : This function Return an array with file information

2)is_file(file path) : Checks wheather the file exist or not & Returns Boolean value.

3)file_get_contents(file Path) : Returns the file content as a string.

4)file_put_contents(fiel path,data) : Writes the content to the file overwriting old content and if file does not exists, creates a new file & adds the content.This function is introduced in 5th version.

Page 109: PHP HTML CSS  Notes

109

5)file(file path) : Returns the file content as an array with each line in the file at a particular index position.

6)filectime(path) : Creates the time of the file.

7)fileatime(file path) : Last access time of the path file.

8)filemtime(file path) : Last modified time of the file.

9)unlink(file path) : Removes the file from the location.

10)filesize(file path) : Returns the size of the file in bites

11)filetype(file Path) : Returns the type of the file (dir or file)

12)fopen(file path,mode) : Opens the file in the specified mode and returns a file handler for handling the file.

13)fread(file handler, size) : Reads the file content from the current file handler position upto the specified size.

14)$fp -> file Pointer ..The internal handler which is used for handling the file.

15)fgetc(file handler) : Reads a single char in the string.

16)fgets(file handler) : Reads a single line from the file..

17)fgetss(file handler) : Reads a single line from the file stripping of html tags in the file.

18)fwrite(file handler) : This function is used to write the content to the file

19)ftell(file handler) : Returns the file handler position in the file

20)fseek(file handler) : Moves the file handler to the specified position in the file

21)fclose(file handler) : Closes the File handler connection.

List of Modes :

r --> Read Mode

Page 110: PHP HTML CSS  Notes

110

r+ --> Read and Write.

w --> Write Mode

w+ --> Write & Read.

a --> Append (also writing but without overwriting files)

a+ --> append & read.

x --> Creates a new file & write..

x+ --> Creat a new file for write and read.

rb,rb+,wb,wb+,ab,ab+,xb,xb+ are the modes to be used for binary files.

Examples for above specified actions :

-----fileput.php

<?php

$file = 'a.txt';

file_put_contents($file,str_repeat("MOd ",5));

?>

-----create.php

<?php

$file = 'c.txt';

$fp = fopen($file,"x");

fwrite($fp," Created");

fclose($fp);

if(is_file($file)){

echo file_get_contents($file);

}

Page 111: PHP HTML CSS  Notes

111

?>

-----write.php

<?php

$file = 'b.txt';

$fp = fopen($file,"w");

fwrite($fp,"Modified");

fclose($fp);

if(is_file($file)){

echo file_get_contents($file);

}

?>

-----read.php

<?php

$file = 'test.txt';

$fp = fopen($file,"r");

echo "Pos : ",ftell($fp),'<br>';

echo fread($fp,3),'<br>';

echo "Pos : ",ftell($fp),'<br>';

echo fgetc($fp),'<br>';

echo "Pos : ",ftell($fp),'<br>';

echo fgets($fp),'<br>';

echo fgets($fp),'<br>';

echo 'Pos : ',ftell($fp),'<Br>';

echo fgets($fp),'<br>';

Page 112: PHP HTML CSS  Notes

112

fseek($fp,35);

echo fgetss($fp),'<br>';

fclose($fp);

?>

-----func.php

<?php

$file = 'test.txt';

var_dump(is_file($file));

echo '<br>';

echo "size : ",filesize($file),'<br>';

echo "Type : ",filetype($file),'<br>';

echo "Created : ",date("d-m-y h:i:s",filectime($file)),'<br>';

echo "Accessed : ",date("d-m-y h:i:s",fileatime($file)),'<br>';

echo "Modified : ",date("d-m-y h:i:s",filemtime($file)),'<br>';

echo file_get_contents($file),'<br>';

echo "<pre>";

print_r(file($file));

echo '<br>';

print_r(stat($file));

?>

-----append.php

<?php

$file = 'b.txt';

$fp = fopen($file,"a");

Page 113: PHP HTML CSS  Notes

113

fwrite($fp,"Append");

fclose($fp);

if(is_file($file)){

echo file_get_contents($file);

}

?>

-----unlink.php

<?php

$file = 'a.txt';

unlink($file);

?>

f)Directory Functions:

1)getcwd() : Current working directory,

2)chdir(path) : Change current working dir to argumented path.

3)is_dir(path) : Checks wheather the argumented dir exist or not and return Boolean value.

4)mkdir(dirname) : Makes a directory on the current working location.

5)rename(old name,new name): Changes the name of the directory.

6)rmdir(dir name) : Removes the directory.

7)scandir(path) : Scan the directory and return the directory content as an array. Returns an array with related path information.

-----getcwd.php

<?php

echo 'Cwd : ',getcwd(),'<br>';

Page 114: PHP HTML CSS  Notes

114

$a = scandir('.',0);

foreach($a as $k=>$v){

echo "$k == $v<br>";

}

chdir('..');echo '<hr>';

echo 'Cwd : ',getcwd(),'<br><hr>';

$a = scandir('.',0);

foreach($a as $k=>$v){

echo "$k == $v<br>";

}

?>

-----mkdir.php

<?php

$dir = 'test';

if(!is_dir($dir)){

mkdir($dir);

echo "Directory is created";

} else {

echo "Directory already exists";

}

?>

-----rename.php

<?php

$dir = 'test';

Page 115: PHP HTML CSS  Notes

115

$new = "modified";

if(is_dir($dir)){

rename($dir,$new);

echo "Directory name is $new";

}

else {

echo "Directory does not exists";

}

?>

-----rmdir.php

<?php

$new = "modified";

if(is_dir($new)){

rmdir($new);

echo "Directory is removed";

}

else {

echo "Directory does not exists";

}

?>

scandir.php

<?php

echo '<pre>';

var_dump(scandir('.'));

Page 116: PHP HTML CSS  Notes

116

?>

Super Globals : Difference between GET and POST :

GET POST

1.GET data transfers through URL. POST data is send through request headers

2.GET is insecure POST is secure

3.File cannot be transfered using GET Files can be transfered

4.Limited data can be send based on length We can send huge data(8MB) which can be scaled

of URL supported by browser(2KB). up by using POST_MAX_SIZE

5.It is fast It is not as fast as GET.

6.$_GET is used for accessing $_POST is used for accessing the GET parameters the POST parameters

GET Ex :

-----get.php

<?php

if(isset($_GET['submit'])){

echo 'Name : ',$_GET['fname'],'<br>';

echo 'Email Address : ',$_GET['email'],'<br>';

$gend = ($_GET['gender'] == 'm')?'Male':'Female';

echo 'Gender : ',$gend,'<br>';

}

Page 117: PHP HTML CSS  Notes

117

echo '<hr>';

echo urldecode($_SERVER['QUERY_STRING']);echo '<hr><br>';

?>

-----get.html

<form method='GET' action='get.php'>

Name : <input type='text' name='fname' value=''><br>

E-Mail : <input type='text' name='email' value=''><br>

Gender : <input type='radio' name='gender' value='m'> Male <input type='radio' name='gender' value='f'> Female<br>

<input type='submit' name='submit' value='Register !'>

</form>

POST Ex :

-----post.php

<?php

if(isset($_POST['submit'])){

echo 'Name : ',$_POST['fname'],'<br>';

echo 'Email Address : ',$_POST['email'],'<br>';

$gend = ($_POST['gender']=='m')?'Male':'Female';

echo 'Gender : ',$gend,'<br>';

$a = $_POST['course'];

echo $a,'<br><hr>';

print_r($a);

}

echo '<hr>';

Page 118: PHP HTML CSS  Notes

118

echo 'The query string : ',$_SERVER['QUERY_STRING'],'<br>';

?>

-----post.html

<form method='POST' action='post.php'/>

Name : <input type='text' name='fname' value=''/><br>

E-Mail : <input type='text' name='email' value=''/><br>

Gender : <input type='radio' name='gender' value='m'/> Male <input type='radio' name='gender' value='f'/> Female <br>

Hobbies : <br>

<input type='checkbox' name='course[]' value='c'/> C-Language <br>

<input type='checkbox' name='course[]' value='p'/> PHP <br>

<input type='checkbox' name='course[]' value='j'/> Java <br>

<input type='submit' name='submit' value='Register'/>

</form>

Server Variables :

-----servervariables.php

<?php

echo 'Get Environment : ',getenv('os'),'<br>';

echo 'Environment Path : ',getenv('path'),'<br>';

echo '<hr>';

echo 'Document Root : ',$_SERVER['DOCUMENT_ROOT'],'<br>';

echo 'Http Host : ',$_SERVER['HTTP_HOST'],'<br>';

echo 'Referer : ',$_SERVER['HTTP_REFERER'],'<br>';

echo 'Method : ',$_SERVER['REQUEST_METHOD'],'<br>';

Page 119: PHP HTML CSS  Notes

119

echo 'User Agent : ',($_SERVER['HTTP_USER_AGENT']),'<br>';

echo 'Name of Script : ',$_SERVER['SCRIPT_NAME'],'<br>';

echo 'Query String : ',$_SERVER['QUERY_STRING'],'<br>';

echo 'Remote Ip Address : ',$_SERVER['REMOTE_ADDR'],'<br>';

echo 'PHP Self : ',$_SERVER['PHP_SELF'],'<br>';

echo 'Request URL : ',$_SERVER['REQUEST_URI'],'<br>';

echo 'Script File Name : ',$_SERVER['SCRIPT_FILENAME'],'<br>';

?>

-----phpinfo.php

<?php

echo phpinfo();

?>

Include_once and required _once : These both will include file very first time and if already file has been included this will not include for the second time.

Defference between include_once & include : Include and include _once will include the files. But if the path of the file is wrong include and include_once will generate the wrong message and rest of the code will be excuted.

Required and required_once : If location of the path is given wrong this will through a wrong as well as path error and code gets halted or the execution will be stop.

Ex : a.php

<style>

b{color:green;}

</style>

<b>I am included</b><br><hr>

Page 120: PHP HTML CSS  Notes

120

<?php

$a = 10;

if(!function_exists('r')){

function r(){

echo 'I am in a.php and working fine<br>';

}

}

?>

b.php

<?php

include_once("a.php");

include("a.php");

include("a.php");

$b = 20;

echo 'The Value of $a = ',$a,'<br>';

echo 'The Value of $b = ',$b,'<br>';

r();

?>

Headers : Headers are the information which are exchanged between client and server for every request and response.

Headers are of two types.

a) Request Headers.

b) Response Headers.

Page 121: PHP HTML CSS  Notes

121

a) Request Headers : These are send from client to server.

HTTP Request : GET/php7/info.php HTTP/1.1

Host : localhost

User_Agent : Mozilla/5.0

Accept : text/HTML, application/html

Accept_encoding: gzip,deflate

Connection : keep-alive

keep-alive : 115

Accept_char : ISO-88591-1 utf-8;q=0.7

Ex : apache_request_headers()

b) Response Headers : These are send from server to client.

X-powered-by : php/5.3.1

keep_Alive : timeout=5,max=100

connection : Keep_Alive

Transfer_Encoding : chunted

content_type : text/html

Ex : apache_response_headers()

HTTP Methods :

For every request from the client to server can be made through various HTTP methods like

GET, POST, PUT, DELETE, HEAD

Headers can be send from php program to the server.

1. headers_list() : Returns an array to the list of the headers which can be shared from server to client.

Page 122: PHP HTML CSS  Notes

122

2. headers_sent() : Returns the boolean value above whether the headers were send to the client or not.

3.header("<name>:<value>") : Header function should be used in the page before any output is send to the page.

Header functions are used for redirection and for sending the output and also for downloading of the files.

Php content in different formats(content type like html,xhtml,images,pdf,flash,video etc).

Ex :

-----hrds.php

<?php

ob_start();

print_r(apache_request_headers()); echo '<hr>';

var_dump(headers_sent());

header("Name:Rajesh");

header("location:info.php");

print_r(headers_list());

echo '<hr>';

print_r(apache_response_headers());

?>

-----info.php

<?php

echo phpinfo();

?>

Page 123: PHP HTML CSS  Notes

123

Downloading :

Step 1: Download of a file is done by sending few headers followed with reading of source file from the server sending a content type header.

header("Content-Type:<mine Type>");pdf -> application/pdf.html -> text/html.jpg/png/gif -> image/(jpg || png || gif).

Step 2: Sending a content Disposition header which will tells the browser to open the file or to ask the user about the file.

header("Content-Disposition:<mode>;filename=<filename>");

----->Inline----->attachment

Step 3: Optionally we can sent content length header with the size of the file.

header("Content-Length:<filesize(finename)>");

Reading the Original file :

readfile(<path of file>) Reads the file Content and prints to the browser.

Ex : download.php

<?php

$file="01.jpg";

$type="image/jpg";

$mode="inline";

header("Content-Type:".$type);

header("Content-Disposition:".$mode.";filename=".$file);

Page 124: PHP HTML CSS  Notes

124

header("Content-Length:".filesize($file));

readfile($file);

?>

----down.php

mage down <a href="download.php"/>View Please</a>

File Uploading :

upload_tmp_dir(<path>) : default is set to c:\xampp\tmp. The temporary location to which the file can be uploaded to the server.upload_max_filesize : (<128>) The max size for a single file which can be uploaded to the server -> max_file_uploads : 20.

Functions in upload :

copy of source destination : Copy the file from source location to destination folder is_upload_file(source path): Checks wheather file upload or not and return boolean.move_upload_file (<source path, destination>): Moves the file from source location to destination location

Predefined variables: - $_FILES is predefined super global file which will be loaded with the

Properties in file upload :

1. $_FILES[<file_field_name>]['name']: It returns the original name of the uploaded file.

2. $_FILES[<file_field_name>]['tmp_name']: It returns the temporary path to the uploaded file.

(It acts as the source path of the uploaded file in the program).

3. $_FILES[<file_field_name>]['size']: It returns the size of the uploaded file in bytes.

Page 125: PHP HTML CSS  Notes

125

4. $_FILES[<file_field_name>]['type']: It gives the MIME (Multipurpose Internet Main Extension) type for the uploaded file.

5. $_FILES[<file_field_name>]['error']: It returns the error code associated with the file upload.

If its value is configured to zero indicates no error.

Ex : testupload.php

<?php

if(isset($_POST['submit'])){

if(isset($_FILES['photo'])){

$src = $_FILES['photo']['tmp_name'];

$desc = "pics/".getRandString(12).$_FILES['photo']['name'];

if(move_uploaded_file($src,$desc)){

echo 'Image saved successfully<br>';

} else {

echo 'Image not saved<br>';

}

}

}

echo '<hr>';

function getRandString($size){

$a = str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');

return addslashes(substr($a,0,$size));

}

Page 126: PHP HTML CSS  Notes

126

?>

-----test.php

<form action='testupload.php' method='POST' enctype='multipart/form-data'/>

Upload Photo : <input type='file' name='photo'/> <input type='submit' name='submit' value='Upload'/>

</form>

COOKIES :Cookies are super global variables which can be stored at client machine.

$_COOKIE: It is a predefined super global variable which can be used for reading cookie data.

setcookie(<name>,<value>): It is a predefined function for creating, updating or deleting the cookie variable at server machine.

cookie values are stored at the browser of client's machine

cookies are not safe for storing the information.

Every webbrowser is limited to a certain number of cookies to be stored at the client's machine(~20).

Cookies information will be exchanged between the client and server every request and response through headers.

If Cookie is once created can be accessed from the next request from the server to the client but not in the same page.

setcookie(<name>,<value>,[<lifetime>],[<domain>],[<path>],[<secure protocol>])

lifetime: Timestamp upto which cookie must be active.

time()+24*60*60

Page 127: PHP HTML CSS  Notes

127

domain: news.abc.com

gmail.com

path: Default path is current working directory

/ Points to root directory

/abc Cookie is shared with all files in abc folder

secure_protocol: If it is true then it will be exchanged with https protocol otherwise with http protocol

Cookie can be created in two ways.

1. By creating cookie with empty value.

2. By creating the cookie in the past

Ex : create.php

<?php

ob_start();

print_r($_COOKIE);

setcookie('c',10,time()+3600);//set cookie

echo "<br>";

print_r($_COOKIE);

setcookie('c',88,time()+3600);//modify or update

echo "<br>";

setcookie('c',"",time()+3600);//delete

echo "<br>";

setcookie('c',"abc",time()-3600);//delete

echo "<br>";

?>

Page 128: PHP HTML CSS  Notes

128

setcookie will sends a header to the server(No output is sent before using.)

If output is started before it use output buffering.

SESSIONS :

It is used for maintaining the state of the user between his login and logout. Session information is stored at the server machine and is accessable with the pages where session is started.

$_SESSION is a predefined super global used for managing session data.

Configuration Settings:

session.auto_start(OFF) : Controls whether the session must be automatically started or not.

session.name=PHPSESSID: The default name at which session id is stored at a client machine as cookie variable.

session.use_cookie(ON*/OFF): Using the cookies for storing the session id value.

session.use_only_cookies: Using cookies only for storing the session id.

session.use_trans_sid(0/1): Using a transferable session id through URL.

session.gc_maxlifetime(1440(24minutes)): The maximum time for which the session data can be maintaines when the user is idle before sending to gc(garbage collector).

Functions in SESSIONS :

session_start(): Starts a new session for the user, if session already axists uses the already existing session.

session_name[<optional_name>]: Gets or sets the name of the session.

Page 129: PHP HTML CSS  Notes

129

session_id(): It returns the session id created for the user. A session id is a unique 32 character length alphanumeric value.

session_regenerate_id : Changes the session id to new one for the user.

session_unset: Erases the session data for the user.

session_destroy: Session will be destroyed.

Ex : session.php

<?php

ob_start();

session_start();

echo 'Session Name : ',session_name(),'<br>';

echo 'Session Id : ',session_id(),'<br>';

echo 'Session Name : ',session_name('Rajesh'),'<br>';

echo 'Session Name : ',session_name(),'<br>';

echo 'Session generate Id : ',session_regenerate_id(),'<br>';

echo 'Generated Id : ',session_id(),'<br>';

echo 'Life time : ',(ini_get('session.gc_maxlifetime')/60),' mins<br>';

echo 'Session save Path : ',ini_get('session.save_path'),'<br>';

echo 'Cookie Save Path : ',ini_get('session.cookie_path'),'<br>';

$_SESSION['Name'] = 'Praveen';

$_SESSION['Email'] = '[email protected]';

print_r($_SESSION); echo '<hr>';

print_r($_COOKIE);echo '<hr>';

session_destroy();

echo 'Session Id : ',session_id(),'<br>';

Page 130: PHP HTML CSS  Notes

130

print_r($_SESSION);

unset($_SESSION['Name']);echo '<hr>';

print_r($_SESSION);

echo '<hr>';

print_r($_COOKIE);

?>

Global Configuration Settings :

Understanding Configuration settings in PHP:

1) POST_MAX_SIZE : Max size of post data that a php will accept

2) magic_quotes_gpe : Escaping of " Quotations with a backslash for the data which is sent through GET,POST,COOKIE & ENV variables.Default value is set to ON.

3) Register_globals : Possible values are ON and OFF. By default is OFF. Registering of super global variable as regular variables in this page is controlled with this settings

4) variables_order : "GPCS";The order which superglobal variable are loaded with the current working page

5) Register_long_arrays : ON or OFFThe availability of superglobals array with login array names used in the older version of PHP is controlled with this settings.

6) file_uploads: ( ON) whether to allow HTTP Files to upload or not;

Buffer : Buffering of the output before sending with browser can be handled by using output buffering.

Configuration settings :

Output_buffering = 4096

Page 131: PHP HTML CSS  Notes

131

Buffers the output upto 4KB and releases the output.

Functions :

ob_start() : Starts the buffering output if buffering is inactive.

ob_get_length : It returns the size of buffer content in the page

ob_flush() : It sends the buffer content to the browser.

ob_get_flush() : It returns the buffer content as a string and sends the buffer to the browser.

ob_clean() : It clears the buffer and stops the buffering.

ob_get_clean : It cleans the buffer content and returns it as a string.

Note : Output buffering is used when we are working with sessions using headers with in the page.

Ex : buffer.php

<?php

ob_start();

echo 'Line 01<br>';

echo 'Line 02<br>';

echo ob_flush(); //implicit_flush = Off;

header("Name:Rajesh");

//echo ob_get_length();

echo '<hr>';

echo ob_get_contents();

?>

Page 132: PHP HTML CSS  Notes

132

Page 133: PHP HTML CSS  Notes

133

MySQLMySQL is a Open Source database server which is developed on top of C & C++ Languages.

MySQL supports many programming & Scripting languages for providing access to the data like C,C++,Java,.Net,PHP,PERL,Python etc..

MySQL was initially developed by MySQL-AB Group of sweaden, which was merge with Sun Microsoft system in Aug 8th, 2008..

MySQL Supports ANS Based SQL FOR Communicating with database server MySQL will allow the SQL statement to get executed through various channel like.

1) GUI Tools(Graphic user Interface),MySQL Administrator, SQLyog, SQL etc

2) Web Based Tools(phpmyadmin, SQL ETC...)

3) Command Line Interface : Accessing local database Server Locally

4) Data : This is collection of information

Database : It is a collection of Data

DBMS :

DBMS stands for Data Base Management System.It Suggests the internal Organization in Database Server.

DBMS is used for defining Structural architecture of data base and internal organization of the data in Various types of DBMS.

1)HDBMS (Hierarchical Data Base Management System)

2)NDBMS (Network Data Base Management System)

Page 134: PHP HTML CSS  Notes

134

3)RDBMS (Relational Data Base Management System)

4)ODBMS (Object Data Base Management System)

5)ORDBMS(Object Based Relational Data Base Management System)

RDBMS :

In RDBMS db is considered as a collection of tables, each table is a collection of records, and each record consists of collection of data set (cols,rows).

E.F.CODD : 12 Rules of RDBMS..can be found at (http://www.cse.ohio-state.edu/~sgomori/570/coddsrules.html)

Normalization :

5 Forms(1st three has to understood);

SQL : Structural Query Language which is used for Communicating with data base Server.

Database Server : It is a Software which will receive the request in SQL and sends the data as the response.

Eg: MySQL,Oracle,Sybase,Postgre SQL,DB2,MSSQL,MS AXIS etc..

SQL:

a)DDL(Data Defination Language)

CREATE -------------|---> Database

| Table

|

|

DROP ---------------|---> Database

| Table

Page 135: PHP HTML CSS  Notes

135

|

ALTER---------------|--->Used for Tables

| ADD

| CHANGE

| DROP

TRUNCATE------------|--->TABLE

b)DML (Data Manipulation Language)

| INSERT INTO

| UPDATE SET

| DELETE FROM

c)DRL (Data Retrivel Language)

| SELECT | WHERE <cond>

| ORDERED BY <field-Name>

| GROUP BY <field-Name>

| LIMIT <start>,<end>

d)DCL (Data Controlling Language)

| ADMIN ZONE

e)TCL (Transaction Control Language)

| Giving Special Permission.

Data Base Level Query :

SHOW DATABASES Return the List of Databases

CREATE DATABASE <db_name> Creates a database if it is not Existing.

Page 136: PHP HTML CSS  Notes

136

a)USE <db_name> Select a database for executing further Queries in the Table.

b)DROP DATABASE<db_name> Deletes the database from the database server Completely with its Tables and data.

Table Level Query :

SHOW TABLES[FROM <db_name>];

CREATE TABLE <table_name> (<field_name> <datatype>[<size>] <add_parementers> <field_info);

ALTER TABLE <table_name> ADD <field_info>;

CHANGE <field_name> <new_field_info>;

ALTER TABLE <table_name> DROP <field_name>;

RENAME <new_name>;(Renaming a Table)

TRUNCATE <table_name>;

This will empty the table. Removes the complete data of the table but the structure of table remains same in the database.

DROP<table_name>; Removes the table data and its Structure;

Data Level Query :

Data manupulation Language:

INSERT INTO <tbl_name> [(<field_list>)] VALUES [(<value_list>),(<value_list2),(value_list3)...];

UPDATE <tbl_name> SET <field_name> = <new_value> WHERE <cond>;

DELETE FROM <tbl_name> WHERE <cond>;

Data Retrival Query:

Page 137: PHP HTML CSS  Notes

137

SELECT (* or <field_list>) FROM <tbl_name> [WHERE <cond>] ORDER BY <field_name> ASC/DESC [GROUP BY <field_name> LIMIT <start_index>[,<length>]];

Numerical Datatypes in MYSQL :

1) Tiny Int : [2pow8 -1] 0-255 UNSIGNED

[-128-127] SIGNED

2) Small Int : 2 bytes [2pow16-1] UNSIGNED

-32767 TO -32767 SIGNED

3) Mediun Int : 3 bytes [2pow24-1]

UNSIGNED int [16777215]

SIGNED int [-8388607]

4) Int : 4 bytes [2pow31-1]

SIGNED Int Range [2147483647]

5) BigInt : 8 bytes [2pow64-1]

0 - 1.84467440737096e+14 20digits

Size of integer will specify the total number of digits

Additional Parameter SIGNED OR UNSIGNED default Value is SIGNED.

6) float(<no of digits>,<precision>) :

A small number with a floating Value .10POW38 0-24(falls in float)

7) Double(no of digits>,<precision>) :

A Large Number with a floating Decimal Point(25-5)

8) Decimal() : A double stored as a string, allowing for a fixed decimal point.

9) Char() : A fixed Section from 0 to 255 character Long.

10) varchar() : A variable section from 0-255 char long.

Page 138: PHP HTML CSS  Notes

138

Miscellaneous Types :

ENUM() : ENUM stands for Enumeration, which means that each coloumn may have one of a specified possible Value.

Text : String Content 65kb for this size is needed.

medium text : 0 - 16777215 char (16mb) can be accomidated in medium text..

long text : 0 to upto 4gb long text

ENUM :

ENUM is a Miscellaneous datatype . Enumeration field used for storing Optional values among which one value can be selected while inserting (0-65535) maximum number of optiona, which are allowed all string values must be enclosed in "Quotations" while inserting.

Date Data types :

Date : YYYY-MM-DD

(0000-9999) allowed dates

Time : hh:mm:ss

Date & Time : YYY-MM-DD hh:mm:ss

TIME STAMP : Defaultly insert the current date and time values.

yyyymmdd hhmmss 14

yyyymmdd hhmm 12

yymmddhhmm 10

yyyymmdd 8

yymmdd 6

Year : 4-digits Year number ,all date values must be enclosed in Quotations during the insertion.

Binary Data Types :

Page 139: PHP HTML CSS  Notes

139

Binary : Fixed length binary content (similar to char)

Var binary : it is variable length binary content similar to varchar.

Blob : binary Large Object similar to text data type

Medium Blob : Similar to medium Text.

Long Blob : similar to Long Text.

Additional Parameters :

1) PRIMARY KEY : Atleast one field in a table must be declared as primary key, it is UNIQUE it is by default an INDEX for the table. it can't be NULL.

2) FOREIGN KEY: The field which establish a relation to the primary key field of the table is foreign Key.

3) UNIQUE : The field apart from primary Key which needs to be UNIQUE can be applied with this field..

4)CURRENT_TIMESTAMP : Predefined constant which can store current time stamp value by default at the time of inserting the date or time. On update current-time stamp it is used for adding current time stamp at the time of updation.

5) AUTO_INCREMENT : Increase the value by one automatically for every row record entry.

Create

CREATE TABLE eg_user(Id SMALLINT(5) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, EmailId VARCHAR(100) NOT NULL UNIQUE, Pword CHAR(32) NOT NULL, Gender ENUM('Male', 'Female') NOT NULL,DateOfBirth DATE NOT NULL,RegisteredOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, uStatus ENUM('Inactive', 'Active') NOT NULL);

DESC eg_user;

Page 140: PHP HTML CSS  Notes

140

DESCRIBE eg_user;

EXPLAIN eg_user;

Inserting records

INSERT INTO eg_user (EmailId, Pword, Gender, DateOfBirth) VALUES ('[email protected]', MD5('abc'), 'Male', '12-12-1980');

List all records of table

SELECT * FROM table_name;

Inserting multiple records

INSERT INTO eg_user (EmailId, Pword, DateOfBirth, Gender) VALUES ('[email protected]', MD5('1'), '1979-10-19', 'Male'), ('[email protected]',MD5('a'), '1980-5-12', 'Female'), ('[email protected]',MD5('ab'), '1972-6-10', 'Male'), ('[email protected]',MD5('AB'), '1989-12-12', 'Female');

Modifying the record

UPDATE eg_user SET DateOfBirth='1980-12-8', uStatus='Active' WHERE Id=1;

Deleting the record

DELETE FROM eg_user WHERE Id=5;

TRUNCATE TABLE tbl_name;

Example :

Create emp table

CREATE TABLE eg_emp(

Id SMALLINT(5) UNSIGNED PRIMARY KEY AUTO_INCREMENT,

Name VARCHAR(30) NOT NULL,

Page 141: PHP HTML CSS  Notes

141

Salary DECIMAL(10,2) NOT NULL,

Location VARCHAR(50) NOT NULL) AUTO_INCREMENT=101;

Inserting Records

INSERT INTO eg_emp (Name, Salary, Location) VALUES ('Mr.A',5000, 'Hyd'),('Mr. B', 4500, 'Mumbai'), ('Ms. C', 6000,'Delhi'), ('Mr. D', 7000, 'Delhi'),('Mr. B', 5000, 'Hyd'),('Ms. E', 3000, 'Hyd');

Read records for only specified columns Name, location

SELECT Name, Location FROM eg_emp;

List emps with salaries < 5000

SELECT * FROM eg_emp WHERE Salary<5000;

List emps whose salary is either 3000, 5000, 4000, 7000

SELECT * FROM eg_emp WHERE Salary=3000 OR Salary=5000 OR Salary=4000 OR Salary=7000;

SELECT * FROM eg_emp WHERE Salary IN(3000,5000,4000,7000);

List emps whose salaries are between 5000 & 8000

SELECT * FROM eg_emp WHERE Salary>=4500 AND Salary<=8000;

SELECT * FROM eg_emp WHERE Salary BETWEEN 5000 AND 8000;

List users born between 1-1-1970 and 31-12-1980

SELECT EmailId, DateOfBirth, Gender FROM eg_user WHERE DateOfBirth BETWEEN '1970-1-1' AND '1980-12-31';

SELECT CURRENT_DATE;

SELECT CURRENT_TIME;

SELECT MONTH(CURRENT_DATE)

Page 142: PHP HTML CSS  Notes

142

SELECT MONTHNAME(CURRENT_DATE);

SELECT WEEKDAY(CURRENT_DATE)

SELECT DAY(CURRENT_DATE)

SELECT DAYNAME(CURRENT_DATE)

SELECT EmailId, DateOfBirth FROM eg_user WHERE MONTH (DateOfBirth) = 12;

SELECT COUNT(Id) FROM eg_user;

SELECT SUM(Salary) FROM eg_emp;

SELECT SUM(Salary) FROM eg_emp

WHERE Location='Hyd';

SELECT MAX(Salary) AS HighestSalary FROM eg_emp;

SELECT MIN(Salary) LeastSalary FROM eg_emp;

Number of emps for every location

SELECT COUNT(*) TotalEmps, Location FROM eg_emp

GROUP BY Location;

Number of emps for every location with salary > 4000

SELECT COUNT(*) TotalEmps, Location FROM eg_emp

WHERE Salary>4000

GROUP BY Location;

List of locations with 2 or more emps having salary>4000

SELECT COUNT(*) TotalEmps, Location FROM eg_emp

WHERE Salary>4000

GROUP BY Location

HAVING TotalEmps>1;

Salary in descending order

Page 143: PHP HTML CSS  Notes

143

SELECT * FROM eg_emp

ORDER BY Salary DESC;

//Salary in desc, with Id desc

SELECT * FROM eg_emp

ORDER BY Salary DESC,

Id DESC;

List second highest earner

SELECT * FROM eg_emp

ORDER BY Salary DESC

LIMIT 1,4;

Create Another Table

CREATE TABLE brand(Id TINYINT(2) UNSIGNED PRIMARY KEY AUTO_INCREMENT,BrandName VARCHAR(50) NOT NULL);

INSERT INTO brand(BrandName) VALUES ('Adidas'),('Nike'),('Nokia'),('Titan'),('Lg');

CREATE TABLE category(Id TINYINT(2) UNSIGNED PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(50) NOT NULL);

INSERT INTO category(Name) VALUES ('Mobiles'),('TShirts'),('Jeans'),('Watches'),('Electronics'),('books');

CREATE TABLE products(Id SMALLINT(5) UNSIGNED PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(50) NOT NULL,Amount DECIMAL(10,2) NOT NULL,in_Stock TIMESTAMP DEFAULT CURRENT_TIMESTAMP,c_id TINYINT(2) UNSIGNED NOT NULL,b_id TINYINT(2) UNSIGNED NOT NULL);

INSERT INTO products(Name,Amount,c_id,b_id) VALUES

('Smart watch',612.954,4,4);

Page 144: PHP HTML CSS  Notes

144

SELECT * FROM products,category;

SELECT p.Name,p.Amount,c.Name FROM products p,category c;

SELECT p.Name Products,p.Amount,p.in_Stock,c.Name Category FROM products p,category c WHERE p.c_id = c.Id;

SELECT p.Name Products,p.Amount,p.in_Stock,c.Name Category,b.BrandName FROM products p,category c,brand b WHERE p.c_id = c.Id AND p.b_id = b.Id ORDER BY Amount DESC;

PHP by Default Support With Mysql library,,

PHP communication with Mysql can be Splitted int some steps like

1) Connecting to the Database

2) Selecting to the Database

3) Query the Database

4) Fetching the Records or Getting the records From Query or Query String.

5) Close the Connection.

1) Connecting to the Database

Among them We have

A) Normal Connection B) Persistance Connection

Normal Connection : Will be active for the Single Program, A Normal Connection can be Closed by Using mysql_close();

mysql_connect('hostname','username','password');

B) Persistance Connection : A Persistance Connection is a Permanent Connection Once establish it cannot be closed.

mysql_pconnect('hostname','username','password');

2) Selecting to the Database

Page 145: PHP HTML CSS  Notes

145

mysql_select_db('dbname',[Optional Conn Handler]);

Selects the Argumented data as current data...

Error Handling in Database :

a)mysql_error() : Returns the last Error Message Occured with the data base server.

b)mysql_errno() : Returns the last error code associated with the mysql database Server.

3) Querying the Database :

a) mysql_query(SQL) : Executes the Query with the database server and returns the Query Handler.

b) mysql_affected_rows : Returns the number of rows affected for the last insert, Update or delete Query.

c) mysql_num_rows(Query handler) : Returns the number of records in the resultant for the select Query .

4) Fetching the Records :

a) mysql_fetch_row(Query handler) : Returns a single record set from the database server, as a numerical array and moves the query handler to next record if record does not exist return false.

b) mysql_fetch_assoc(Query handler) : Returns the record Set as an associative array with field names as its index position - if record does not exist return false..

c) mysql_fetch_array(Query handler) : Returns the record set as an array with numerical or associative or both arrays . Returns false if no record found.

d) mysql_fetch_object(Query handler) : Returns the record set as an object with field names as its values .

5) Close the Connection :

Page 146: PHP HTML CSS  Notes

146

a)mysql_close : Close the connection with the data base.

There are 2 other functions in php.Which gives a message.

if not able to connect to database then we can read the message as

die('Message');

die(mysql_errno().' - '.mysql_error()); or exit;

Page 147: PHP HTML CSS  Notes

147

OOPS

Class :

It is a collection of properties (variables) and methods.

Syntax :

class <class_name>

{

//code

}

[abstract|final] class <class_name>

{

//code

}

Property (or) member : A property or member of a class is an identifier which is used for storing data which can be accessible throughout the class.

<public|protected| private>[static] <var> =<value>;

Ex :

public $x=10;

protected $account_no=null;

static public $conv_rate=0.87;

Page 148: PHP HTML CSS  Notes

148

Method :

A method is an action for a class (or) a method is a function inside the class

Syntax :

[static][final|abstract][public*|protected|private] function <fun_name>([args])

{

//code

}

Ex :

function getName()

{

return $this->name;

}

Object :

It is an instance of a class.Object is used for accessing class properties(public). Object can execute methods(public).

Syntax :

<object>=new <class_name>[args];

It is the operator which is used for accessing class properties

and excuting class methods using an object

Ex :

<?php

class A

Page 149: PHP HTML CSS  Notes

149

{

public $x=20;

public function test()

{

echo "Test function<br>";

}

}

$obj=new A;

var_dump($obj);

echo '$obj->x=',$obj->x,'<br>';

$obj->test();

$obj->x=21;

echo '$obj->x=',$obj->x,'<br>';

$obj2=new A;

echo '$obj2->x=',$obj2->x,'<br>';

?>

Constructor :

It is a predefined method which is automatically executed within the class when a class is instantiated. Any argument must be passed to the class at the time of instatiation.

constructor() : It is the predefined name which can be used for the constructor in a class(php>=5.0). For PHP<5.0 version constructor name must be similar to class name.

Ex :

<?php

Page 150: PHP HTML CSS  Notes

150

class Human

{

public $name="ram";

public $age=0;

function getName(){

return $this->name;

}

function getAge(){

return $this->age;

}

function setName($n){

$this->name=$n;

}

?>

$this is a predefined variable which will be instantiated in a class when an object is called.

$surya=new Human;

$surya->name='suryaprakash';

$surya->age=32;

$juli=new Human;

$juli->name='julia robert';

$juli->age=45;

Destructor (>=PHP 5.0) :

The method which will be automatically called when the class object is uninitialised in the program.

Page 151: PHP HTML CSS  Notes

151

destructor() : It is the prereserved name for the destructor.

Class constant :

const <name>=<value>;

Ex :

const X=10;

Class constants are case sensitive. They are suggested to begin with uppercase.Class constants are specific in class, they must be unique with in the class.

:: (Scope Resolution Operator):

It is used for accessing static properties,class constants and Executing static methods.

Accessing the class constant :

Syntax :

<class_name>::<constant_name>

Self : self is a predefined keyword used for refering the same class within the class in scope resolution operator convertion.

Parent : parent keyword refers to the parent class.

Ex : -

<?php

class Person {

private $name;

public function __construct($name) {

$this->name = $name;

}

public function getName() {

Page 152: PHP HTML CSS  Notes

152

return $this->name;

}

public function getTitle() {

return $this->getName()." the person";

}

public function sayHello() {

echo "Hello, I'm ".$this->getTitle()."<br/>";

}

public function sayGoodbye() {

echo "Goodbye from ".self::getTitle()."<br/>";

}

}

class Geek extends Person {

public function __construct($name) {

parent::__construct($name);

}

public function getTitle() {

return $this->getName()." the geek";

}

}

$geekObj = new Geek("Ludwig");

$geekObj->sayHello();

$geekObj->sayGoodbye();

?>

Page 153: PHP HTML CSS  Notes

153

Inheritance :

It inherites the properties and methods of a base class to an extended class is known as inheritance.

Base class : A class from which properties and methods are inherited to child class.Base class can be called as parent class or super class. Extended class or child class or sub class : The class which inherits the properties and methods from a base is known as an extended class or child class or sub class.

Note : PHP supports multi-level inheritance but won't support multiple inheritance.

Multilevel inheritance :

class A

{

}

class B extends A

{

}

class c extends b

{

}

Multiple inheritances :

class X extends Y,Z,W

{

}//wrong

Extends: A predefined key word which is used for inheriting a class.

Ex: -

Page 154: PHP HTML CSS  Notes

154

class A

{

public $x=20;

function test()

{

echo "test method<br>";

}

}

class B extends a

{

}

$b=new B;

echo $b->test();

Overriding :

Redeclaring a method in the base class with the extended class is known as overriding.

Encapsulation :

Hiding of the properties and methods of a class using access specifiers (public,private and protected) is known as Encapsulation.

Access Specifiers :

These are prereserved keywords which are used for controlling the visibility of properties and methods.They are public,protected and private.

Public : A Public property or method which can be accessed or executed through the object and method of same class or through the method of extended class.

Page 155: PHP HTML CSS  Notes

155

Protected : A Protected property or method which can be accessed through method of same class or extended class(They are not accessible through object of same class or extended class).

Private : A Private property or method which can be accessed through the method of same class.(It cannot be accessed through object of parent or child class and through method of child class).

|object of |Method of | Object of | Method of |

|same class|same class|extended class |Extended class |

---------------------------------------------------------------------------------

Public | Yes | Yes | Yes | Yes |

---------------------------------------------------------------------------------

Protected | No | Yes | No | Yes |

---------------------------------------------------------------------------------

Private | No | Yes | No | No |

---------------------------------------------------------------------------------

Ex :

<?php

class A{

public $pub="public property<br>";

protected $pro="protected property<br>";

private $pri="private property<br>";

public function pub()

{

"public Method<br>";

}

protected function pub()

Page 156: PHP HTML CSS  Notes

156

{

"protected Method<br>";

}

private function pub()

{

"private Method<br>";

}

function accessAll()

{

echo "<b>Method of same class</b><br>";

echo $this->pub;

echo $this->pro;

echo $this->pri;

echo $this->pub();

echo $this->pro();

echo $this->pri();

}

}

class B extends A{

function accessAllB{

echo "<hr><b>Method of Extended class</b><br>";

echo $this->pub;

echo $this->pro;

echo $this->pri; //no

Page 157: PHP HTML CSS  Notes

157

echo $this->pub();

echo $this->pro();

echo $this->pri();//no

}

}

$a=new A;//Object of same class

echo "<b>Object of same class</b><br>";

echo $a->pub;

echo $this->pro; //no

echo $this->pri; //no

echo $this->pub();

echo $this->pro();//no

echo $this->pri();//no

$a->accessAll();

$b=new B; //Object of extended class

echo "<b>Object of extended class</b><br>";

echo $b->pub;

echo $b->accessAllB();

?>

Static :

It is a predefined keyword used for declaring static properties or methods. A property defined as static can be accessed through scope resolution operator. It cannot be accessed through object instance. A static method must be executed through scope resolution operator(::). A static method should not use $this keyword inside its code.

Page 158: PHP HTML CSS  Notes

158

Final : It is a predefined keyword used for specifying a class as final or a method as final.

Final class : A class specified as final cannot be extended to other class.

Final method: A method specified as final cannot be overridden in extended class.

Abstraction : abstract is a predefined keyword which is used for defining abstract class or method.

Abstract class : A class with atleast one abstract method must be declared as abstract class. An abstract class cannot be instantiated directly. An abstract class must be extended where abstract methods must be implemented with the code. An abstract class can have properties and constants. An abstract class should not contain private methods.

Abstract methods : An abstract method should not contain body. An abstract method cannot be private. abstract method must be declared in its extended class along with its code.

Ex: -

<?php

abstract class a{

public $x=10;

const X=12;

function abs(){

echo "abstract method<br>";

}

}

class B extends A{

function abs(){

Page 159: PHP HTML CSS  Notes

159

echo "abstract method of extende class<br>";

}

}

?>

Interface :

An interface is a collection of bodyless method without any access specifier. An interface won't allows the usage of declaration of properties or normal methods. An interface cannot be instantiated directly whereas it can be implemented by a class. The class which implements the interface must redeclare its bodyless methods in the class. Multiple interfaces can be implemented by a class.

Implements : It is a predefined keyword which is used for loading an interface to a class.

Page 160: PHP HTML CSS  Notes

160

Page 161: PHP HTML CSS  Notes

161

AJAX

AJAX stands for Asynchronous JavaScript And XML. It is a client side JavaScript method which is used for communication with the server machine without any page refresh.

1. To achieve asynchronous communication between browser and server

2. Updation of certain portions of the current webpage without Reloading the entire webpage.

AJAX is introduced in 2000 by Microsoft,it became very popular From 2005 onwards.

AJAX is a browser dependent client side coding which is used for getting the dynamic content from the server for JavaScript event in the WebPages.

AJAX communication will takes place in few steps.

1. Creating a cross browser compatible AJAX.

2. Opening the request to the server page.

3. Sending the request.

4. Checking the status of the request.

5. On compilation of request loading the responded content

at the target element.

Object in Internet Explorer :

new ActiveXObject('Microsoft.XMLHTTP');

new ActiveXObject('MSXML.XMLHTTP');

new ActiveXObject('MSXML2.XMLHTTP');

Page 162: PHP HTML CSS  Notes

162

new ActiveXObject('MSXML3.XMLHTTP');

new ActiveXObject('MSXMLC.XMLHTTP');

Other than IE :

new XMLHttpRequest();

Opening Request :

if(window.ActiveXObject){

document.write("IE");

}

else if(window.XMLHttpRequest){

document.write("Other than IE");

}

else {

document.write("No Ajax support");

}

Open :

open(method,url,async,[user_name],[password]);

Ex : ajax.open("Get","getuser.php?id=2",true);

Sending the Request :

Send :

send(null|<parameters>)

Ex:-send(ajax.send(null);

Properties of AJAX :

a) Ready State :

Page 163: PHP HTML CSS  Notes

163

0uninitialised(Ajax engine is created,connection is not established)

1initialised(open method will be called,connection established)

2sent(send method is called,request is sent to server)

3loading(request is under process)

4completed(response received,process by AJAX engine completed)

b) On ready state Change :

Predefined event which will be called whenever ready state property value is updated.

Ex :

ajax.onreadystatechange=function(){

if(ajax.readystate==4)

{

document.write("ready state"<br>");

}

else

{

document.write("Not ready state<br>");

}

}

c) Status :

Here we will have the status code of the AJAX.

200-> successful

5xx->server issue

4xx->page issue

Page 164: PHP HTML CSS  Notes

164

3xx->redirection

d) Response Text :

The information send from the server as text content.

ajax.responseText

e) ResponseXML :

Used for accessing response XML.

ajax.responseXML

Flow of AJAX based Application :

1. User action is performed on any of the HTML components Like button, hyperlink, selectbox, textbox etc.

2. Certain JavaScript event is raised because of the above User action

3. Specific user defined JavaScript function is called to handle The above raised JavaScript event.

4. In the above JavaScript function

Logic is written to create Ajax engine Partial form data is gathered Callback (user-defined) function is set to

onreadystatechange Property of AJAX engine. URL is prepared along with every string Connection is established (open method is called) Request is sent to server (send () is called)

5. Request related response comes to AJAX engine as text or XML data.

6. Once again callback function is called. Inside callback function

Logic to take response received by AJAX engine using JavaScript

Page 165: PHP HTML CSS  Notes

165

Logic is written to update certain portions of the currentwebpages without reloading the entire webpage with the receiver response.

Page 166: PHP HTML CSS  Notes

166

JOOMLA

JOOMLA is a content management system. It is a CMS tool. It is developed on php using mysql as its backend.JOOMLA is a object oriented based tool which was developed on the Top of MVC architecture. JOOMLA comes with various predefined templates, components, modules, languages And plug-ins.

JOOMLA software is available in various versions. (JOOMLA1.0.x, JOOMLA1.5.x, JOOMLA1.6.x).

JOOMLA software consists of two interfaces.

1. User interface (front end)

2. Admin interface (Backend)

1. User Interface : Front end is the actual website Which is shown to the actual users of the website.

2. Admin interface : Backend is the interface Which is accessible for the backend users for Managing the website with various actions.

User Management :

It allows the management of the Users to the website. Various types of users are observed.

a)Front end users : Registered

b)Special users : Editor, Publisher

c)Backend users : Manager, Adminstrator, Super administrator.

Media Management :

It is used for managing media files in the software.

Section management :

Section : It is a top level hierarchy for content Classification. It allows the management of sections.

Page 167: PHP HTML CSS  Notes

167

Category management :

A category is the child category for a section used for sub classifying the content.

Article Management :

It can be considered as a webpage In the site which can be classified to a category Or a section.

Component : A component is a functional block in the Website which can be considered as Database Interaction and can be loaded at the main (center) Portion of the website.

Module : It is a functional block which can occupy various pre-defined positions in the software like top,left,right ,user 1,user 2, ….. user n, footer etc. A module can be controlled for its display in One or more pages.

Plug-in : A plug-in is a logical part which will Enhance the way in which we will display the Content of the website.

Template management :

A template is a predefined Interface which is used for switching the user Interfaces on the fly.

Language management :

JOOMLA supports multilingual Sites where we can install language extension for Adding support with additional language.

www.joomla.org

Latest version is 1.7

Installation of JOOMLA :

1. Install joomla without sample data

2. Add all the users for each role

3. Create few categories

4. Create few articles.

Page 168: PHP HTML CSS  Notes

168

5. Add the menu links for the articles category

6. Download free JOOMLA templates and install switch between the templates.

7. Try to change logo of the template

8. Install the external modules and plug-ins

9. Activate free loaded modules and plug-ins.Check their functionality

10. create a website with few links using JOOMLA

Page 169: PHP HTML CSS  Notes

169

Page 170: PHP HTML CSS  Notes

170

JQUERY

JQuery is a JavaScript framework which is used For writing less code and doing more action . JQuery is developed on top of java platform and it is used for creating rich website interface . JQuery is a fast and concise JavaScript library . That simplifies HTML document traversing , event Handling, animating and Ajax interaction for Rapid web development . JQuery is designed to Change the way that you write JavaScript.

www.jquery.comSyntax :

$(selector).method

Special Effects :

Hide ()

Show ()

JQuery

JQuery documents

JQuery core selector

JQuery supports css page selector

Traversing

CSS

Effects

Events

AJAX : implements JQuery plug-ins

Use JQuery pop calendar

Write JQuery cursors

JQuery based tool tips

Page 171: PHP HTML CSS  Notes

171

JQuery based light box

JQuery based form validations

JQuery based news agrigation using AJAX

THE END

Page 172: PHP HTML CSS  Notes

172

Javascrtipt_Interview_Quesions PHP_Interview_questions

Javascrtipt_Interview_Quesions

Page 173: PHP HTML CSS  Notes

173

1) <script type="text/javascript"> x=4+"4"; document.write(x);</script> Output------?a) 44 b) 8 c) 4 d) Error output Ans: a

2) <script type="text/javascript" language="javascript">var qpt = "Vempower Solutions";var result = qpt.split(" ");document.write(result); </script>a) Vempowerb) V,e,m,p,o,w,e,r, S,o,l,u,t,I,o,n,sc) Vempower Solutionsd) VempoweSolutions

Ans: c3) Is it possible to nest functions in JavaScript? a) True b) False

Ans: a

4) <script>document.write(navigator.appCodeName);</script>

a) get code name of the browser of a visitor

Page 174: PHP HTML CSS  Notes

174

b) set code name of the browser of a visitor c) None of the above Ans: a

5) Which of the following is true? a) If onKeyDown returns false, the key-press event is cancelled. b) If onKeyPress returns false, the key-down event is cancelled. c) If onKeyDown returns false, the key-up event is cancelled. d) If onKeyPress returns false, the key-up event is canceled. Ans: a

6) Scripting language are a) High Level Programming language b) Assembly Level programming language c) Machine level programming language Ans: a

7) <script language="javascript">function x(){var s= "Good 100%"; var pattern = /\D/g;var output= s.match(pattern);document.write(output);}</script> a) Good % b) 1,0,0 c) G,o,o,d,% d) Error Ans: c8) <script language="javascript">

Page 175: PHP HTML CSS  Notes

175

var qpt="Sample String "; alert(qpt.charAt(qpt.length-1));</script> a) p b) e c) g d) Error

Ans: c

9) Are java and javascript the same?a) NO b) YES Ans: a

10) Syntax for creating a RegExp object:(a). var txt=new RegExp(pattern,attributes);(b). var txt=/pattern/attributes;Which of the above mentioned syntax will correct?

a) (a) only b) (b) only c) Both (a) and (b) d) None of the above Ans: c

11) <script language="javascript">function x(z,t){alert(x.length);}</script>output:

Page 176: PHP HTML CSS  Notes

176

?a) Error b) 2 c) 1 d) 3 Ans: b

12) What is mean by "this" keyword in javascript?a) It refers current object b) It referes previous object c) It is variable which contains value d) None of the above Ans: a13) In JavaScript, Window.prompt() method return true or false value ? a) False b) True c) None of above Ans: a

14) Math. round(-20.51)=? a) 20 b) -21 c) 19 d) None Ans: b

15) <script language="javascript">function x(){var s = "Quality 100%!{[!!";var pattern = /\w/g;

Page 177: PHP HTML CSS  Notes

177

var output = s.match(pattern);document.write(output);}</script> a) %,!,{,[,!,! b) Q,u,a,l,i,t,y,1,0,0 c) Quality 100 d) Error Ans: b16) <script type="text/javascript" language="javascript">var qpt= new Array();qpt[0] = "WebDevelopment";qpt[1]="ApplicationDevelopment"qpt[2]="Testing"qpt[3] = "Vempower Solutions";document.write(qpt[0,1,2,3]);</script>a) Error b) Vempower Solutionc) WebDevelopment d) WebDevelopmnet,ApplicationDevelopment,Testing,Vempower Solutions Ans: b

17) parseFloat(9+10)=? a) 19 b) 910 c) None Ans: c

18) <script language="javascript">function x(){

Page 178: PHP HTML CSS  Notes

178

document.write(2+5+"8");}</script> a) 258 b) Error c) 7 d) 78 Ans: d

19) In Javascript, Which of the following method is used to evaluate the regular expression?a) eval(2*(3+5)) b) evaluate(2*(3+5)) c) evalu(2*(3+5)) d) None of the aboveAns: a

20) <script language="javascript">function x(){var s= "quality 100%"; var pattern = /\d/g;var output= s.match(pattern);document.write(output);}</script> a) 100 b) 1,0,0 c) q,u,a,l,i,t,y,% d) Error Ans: b21) <script type="text/javascript" language="javascript">

Page 179: PHP HTML CSS  Notes

179

qpt=((45%2)==0)? "hello" : "bye";document.write(qpt);</script> a) hello b) bye c) Error in string handling d) None of the aboveAns: b

22) How do you create a new object in JavaScript?a) var obj = {}; b) var obj = Object(); c) var obj=new {}; d) None of the above Ans: a23) In Javascript, What does isNaN function do ?a) Return true if the argument is not a number. b) Return false if the argument is not a number. c) Return true if the argument is a number. d) None of the above Ans: a24) Which of the following properties hold the values of the pixels of the length of the width and height of the viewer's screen resolution?a) screen.width and screen.height b) Resolution.width and Resolution.height c) screen.pixels.width and screen.pixels.height d) ViewerScreen.width and ViewerScreen.height Ans: a

25)How to assign a function to a variable with the JavaScript

Page 180: PHP HTML CSS  Notes

180

Function contructor ? a) var f=Function("x","y","return x+y"); b) var f=Function(x,y){ return x+y;} c) var f= new Function("x", "y", "return x + y"); Ans: b

26) In JavaScript, Window.alert() is used to allow user to enter somethinga) True b) False c) None of above Ans: b

27) Is Javascript has any date data type?a) Yes b) No Ans: b

28) ?_name is it valid javascript identifier? a) Yes b) No Ans: a

29) <script type="text/javascript" language="javascript">var qpt="V-Empower Solutions ";var result =qpt.lastIndexOf("s");document.write(result);</script> a) -1 b) 18 c) 17 d) 19

Page 181: PHP HTML CSS  Notes

181

Ans: 18

30) <script language="javascript">function sum(x){function add(y){return x+y;}return add;}function callme() { result=sum(5)(5); alert(result); }</script>

If you call the function callme(), what will happen ?

a) 10 b) Error in calling Function c) 5 d) None of the above Ans: a

31) <script type="text/javascript">document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>Can you write HTML tag inside the javascript ? a) No b) Yes c) Impossible Ans: b

32) How to speicfy the color of the hypertext links with JavaScript ?a) document.linkColor="#00FF00";

Page 182: PHP HTML CSS  Notes

182

b) document.LColor="#00FF00"; c) document.LinkC="#00FF00"; d) document.hyperTextLink="#00FF00": Ans: a

33) ------------- converts a string to floating point numbers. a) eval b) ParseInt c) ParseFloat d) None Ans: c

34) In Javascript, Which of the following method is used to find out the character at a position in a string? a) charAt() b) CharacterAt() c) CharPos() d) characAt() Ans: a

35) <script type="text/javascript" language="javascript">

var qpt = "V-Empower Solutions";var result =qpt.substring(7,8);document.write(result);</script>36) What are the following looping structures are available in javascripts?a) for,forecach b) foreach,whileloop c) do-while loop,foreach d) for , while loop

Page 183: PHP HTML CSS  Notes

183

Ans: d

37) Which of these is not a method of the Math object?a) atan() b) atan2() c) eval() d) acos() Ans: c

38) <script type="text/javascript">var s = "9123456 or 80000?";var pattern = /\d{4}/;var output = s.match(pattern);document.write(output);</script>a) 9123 b) 91234 c) 80000 d) None of the above Ans: a

39) In javascript, RegExp Object Method test() is used to search a string and returns a) true or false b) found value c) index d) None of the above Ans: a

40) What property would you use to redirect a visitor to another page? a) document.URL b) window.location.href

Page 184: PHP HTML CSS  Notes

184

c) .document.location.href d) link.href Ans: c

41) -------------- method is used to remove focus from the specified object. a) blur() b) focus() c) None Ans: a

42)Javascript is a ________ typed language. a) tightly b) loosely Ans: b43)Choose the built-in object: a) Password b) Math c) Link d) Hidden Ans: b

44)Choose the object(s) associated with the onFocus event handler: a) Password b) Hidden c) Both d) Neither Ans: a

45)Choose the object(s) associated with the onKeyPress event handler:

Page 185: PHP HTML CSS  Notes

185

a) Document b) Layer c) Both d) Neither Ans: a

46)Choose the best pattern for the string: 840-21-3688 a) /\d+-\d{2,}-?\d*/ b) /\w+-\w+-\w+/ c) /\d+\d+\d+/ d) /\d+-\d?-\d+/ Ans: a

47) Which would JavaScript assign to an uninitialized variable? a) NaN b) null c) undefined d) false Ans: c

48)Which is not a built-in function? a) parseInt() b) exec() c) eval() d) parseFloat() Ans: b

49)Seek the truth about setTimeOut(): a) The statement(s) it executes run(s) only once. b) It pauses the script in which it is called. c) clearTimeOut() won't stop its execution.

Page 186: PHP HTML CSS  Notes

186

d) The delay is measured in hundredths of a second. Ans: a

50)How do you call a function named "myFunction"?a) call function myFunctionb) myFunction()c) call myFunction()

Ans: c

51) What is the correct JavaScript syntax for opening a new window called "window2" ?a)new("http://www.w3schools.com","window2")b)new.window("http://www.w3schools.com","window2")c)window.open("http://www.w3schools.com","window2")d)open.new("http://www.w3schools.com","window2")

Ans: c

52)How do you find the client's browser name?a)client.navNameb)browser.namec)navigator.appName

Ans: c

53) Semicolons are optional at the end of a JavaScript statement.

a)True

b)False

Ans: a

54)Which of the following are capabilities of functions in JavaScript? a) Return a value b) Accept parameters and Return a value c) Accept parameters d) None of the above Ans: c55)Which popup box you use when want a value from user before open a page?

Page 187: PHP HTML CSS  Notes

187

a) alert("Write some text here")b) confirm("Write some text here")c) prompt("Write here some text")d) None of the aboveAns: c56)What is the correct way to write a JavaScript array?a) var txt = new Array("tim","kim","jim")b) var txt = new Array="tim","kim","jim"c) var txt = new Array:1=("tim")2=("kim")3=("jim")d) var txt = new Array(1:"tim",2:"kim",3:"jim")Ans: a57) How to submit form data with javascript?a) document.formname.submit();b) submit()c) document.submit()d)None of the aboveAns: a58) When a user views a page containing a JavaScript program, which machine actually executes the script?

a) The User's machine running a Web browser

b) The Web server

c) A central machine deep within Netscape's corporate offices

d) None of the above

Ans: a

59) Which of the following is not a valid JavaScript variable name?

a) 2names

b) _first_and_last_names

c) FirstAndLast

d) None of the above

Ans:a

Page 188: PHP HTML CSS  Notes

188

60) To set up the window to capture all Click events, we use which of the following statement?

a) window.captureEvents(Event.CLICK);

b) window.handleEvents (Event.CLICK);

c) window.routeEvents(Event.CLICK );

d) window.raiseEvents(Event.CLICK ); Ans: a

PHP_Interview_questions

Question: 1 Who is the father of PHP?

Answer: Rasmus Lerdorf is known as the father of PHP.  

Question: 2 What is the difference between $name and $$name? Answer: $name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.

Question: 3 How can we submit a form without a submit button?

Answer: 3 Java script submit () function is used for submit form without submit buttonon click call document.formname.submit()

Question : 4 In how many ways we can retrieve the data in the result set ofMySQL using PHP?

Answer : 4 We can do it by 4 Ways1. mysql_fetch_row.

2. mysql_fetch_array

3. mysql_fetch_object4. mysql_fetch_assoc

Question : 5 What is the difference between mysql_fetch_object andmysql_fetch_array?

Page 189: PHP HTML CSS  Notes

189

Answer : 5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference -an object is returned, instead of an array. Indirectly, that means thatyou can only access the data by the field names, and not by theiroffsets (numbers are illegal property names).

Question : 6 What are the differences between get and post methods.

Answer : 6 There are some defference between GET and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request

 Question : 7 How can we extract string "pcds.co.in " from a string "http://[email protected] using regular expression of PHP?

Answer : 7 preg_match("/^http:\/\/.+@(.+)$/","http://[email protected]",$matches);echo $matches[1];

Question : 8 How can we create a database using PHP and MySQL?

Answer : 8 We can create MySQL database with the use ofmysql_create_db("Database Name") .

Question : 9 What are the differences between require and include?

Answer : 9 Both include and require used to include a file but when included file not found Include send Warning where as Require send Fatal Error .

Question : 10  Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?Answer : 10   Yes we can use include("xyz.php") more than one time

Page 190: PHP HTML CSS  Notes

190

in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob.

Question : 11   What are the different tables(Engine) present in MySQL, which one is default?

Answer : 11  Following tables (Storage Engine) we can create.

1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. )2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)3. Merge4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. )5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions) 6. EXAMPLE 7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)10. BLACKHOLE (The BLACKHOLE storage engine acts as a "black hole" that accepts data but throws it away and does not store it. Retrievals always return an empty result).

Page 191: PHP HTML CSS  Notes

191

Question : 12  What is use of header() function in php ?

Answer : 12 The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen.

Question: 13 How can I execute a PHP script using command line?

Answer : 13 Just run the PHP CLI (Command Line Interface) program andprovide the PHP script file name as the command line argument.

Question : 14 Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ?

Answer : 14 In php.ini file: set short_open_tag=on to make PHP support .

Question : 15 Shopping cart online validation i.e. how can we configure Paypal, etc.?

Answer : 15 Nothing more we have to do only redirect to the payPal url aftersubmit all information needed by paypal like amount,adresss etc.

Question : 16 What is meant by nl2br()?

Answer : 16 Inserts HTML line breaks (<BR />) before all newlines in a string.

Question : 17 What is htaccess? Why do we use this and Where?

Answer : 17 .htaccess files are configuration files of Apache Server which providea way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particulardocument directory, and the directives apply to that directory, and all subdirectories thereof.

Page 192: PHP HTML CSS  Notes

192

Question : 18 How we get IP address of client, previous reference page etc?

Answer : 18 By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc.

Question : 19 What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and perating systems?

Answer : 19 All of those are open source resource. Security of Linux is veryvery more than windows. Apache is a better server that IIS both infunctionality and security. MySQL is world most popular open sourcedatabase. PHP is more faster that asp or any other scripting language.

Question : 20 How can we encrypt and decrypt a data present in a MySQL table using MySQL?

Answer : 20 AES_ENCRYPT () and AES_DECRYPT ().

Question : 21 How can we encrypt the username and password using PHP?

Answer : 21 The functions in this section perform encryption and decryption, andcompression and uncompression:

encryption Decryption

AES_ENCRYT() AES_DECRYPT()

ENCODE() DECODE()

DES_ENCRYPT() DES_DECRYPT()

ENCRYPT() Not available

MD5() Not available

OLD_PASSWORD() Not available

PASSWORD() Not available

Page 193: PHP HTML CSS  Notes

193

SHA() or SHA1() Not available

Not available UNCOMPRESSED_LENGTH()

 

Question : 22 What are the features and advantages of object-orientedprogramming?

Answer : 22 One of the main advantages of OO programming is its ease ofmodification; objects can easily be modified and added to a system thereby reducing maintenance costs. OO programming is also considered to bebetter at modeling the real world than is procedural programming. Itallows for more complicated and flexible interactions. OO systems arealso easier for non-technical personnel to understand and easier forthem to participate in the maintenance and enhancement of a systembecause it appeals to natural human cognition patterns.For some systems, an OO approach can speed development time since manyobjects are standard across systems and can be reused. Components thatmanage dates, shipping, shopping carts, etc. can be purchased and easilymodified for a specific system.

Question : 23 What are the differences between procedure-oriented languages and object-oriented language?

Answer : 23 There are lot of difference between procedure language and object oriented like below1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model2>In Procedure language it is difficult to use design pattern mvc ,

Page 194: PHP HTML CSS  Notes

194

Singleton pattern etc but in OOP you we able to develop design pattern3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .    

Question : 24 What is the use of friend function?

Answer : 24 Sometimes a function is best shared among a number of differentclasses. Such functions can be declared either as member functions ofone class or as global functions. In either case they can be set to befriends of other classes, by using a friend specifier in the class thatis admitting them. Such functions can use all attributes of the classwhich names them as a friend, as if they were themselves members of thatclass.A friend declaration is essentially a prototype for a member function,but instead of requiring an implementation with the name of that classattached by the double colon syntax, a global function or memberfunction of another class provides the match.

Question : 25 What are the differences between public, private, protected,static, transient, final and volatile?

Answer : 25 Public: Public declared items can be accessed everywhere.Protected: Protected limits access to inherited and parentclasses (and to the class that defines the item).Private: Private limits visibility only to the class that definesthe item.Static: A static variable exists only in a local function scope,but it does not lose its value when program execution leaves this scope.Final: Final keyword prevents child classes from overriding amethod by prefixing the definition with final. If the class itself isbeing defined final then it cannot be extended.transient: A transient variable is a variable that may not

Page 195: PHP HTML CSS  Notes

195

be serialized. volatile: a variable that might be concurrently modified by multiplethreads should be declared volatile. Variables declared to be volatilewill not be optimized by the compiler because their value can change atany time.

Question : 26 What are the different types of errors in PHP?

Answer : 26 Three are three types of errors:1. Notices: These are trivial,non-critical errors that PHP encounters while executing a script – forexample, accessing a variable that has not yet been defined. By default,such errors are not displayed to the user at all – although, as you willsee, you can change this default behavior.2. Warnings: These are more serious errors – for example, attemptingto include() a file which does not exist. By default, these errors aredisplayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors – for example,instantiating an object of a non-existent class, or calling anon-existent function. These errors cause the immediate termination ofthe script, and PHP's default behavior is to display them to the userwhen they take place.

Question : 27 What is the functionality of the function strstr and stristr? Answer : 27 strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string. $email= '[email protected]';$domain = strstr($email, '@');echo $domain; // prints @gmail.comhere @ is the needle stristr is case-insensitive means able not able to differentiate between a and A.    

Page 196: PHP HTML CSS  Notes

196

Question : 28 What are the differences between PHP 3 and PHP 4 and PHP 5?

Answer : 28 There are lot of difference among these three version of php1.Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come 2.Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C In PHP5 1. Implementation of exceptions and exception handling2. Type hinting which allows you to force the type of a specific argument3. Overloading of methods through the __call function4. Full constructors and destructors etc through a __constructor and __destructor function5. __autoload function for dynamically including certain include files depending on the class you are trying to create.6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.7 Interfaces & Abstract Classes8 Passed by Reference : 9 An __clone method if you really want to duplicate an object.

Question : 29 How can we convert asp pages to PHP pages?

Answer : 29 there are lots of tools available for asp to PHP conversion. you cansearch Google for that. the best one is available athttp://asp2php.naken.cc./. 

Question : 30 What is the functionality of the function htmlentities? Answer : 30 Convert all applicable characters to HTML entitiesThis function is identical to htmlspecialchars() in all ways, exceptwith htmlentities(), all characters which have HTML character entityequivalents are translated into these entities.    

Page 197: PHP HTML CSS  Notes

197

Question : 31 How can we get second of the current time using date function?Answer : 31 $second = date("s");

Question : 32 How can we convert the time zones using PHP? Answer : 32 By using date_default_timezone_get and date_default_timezone_set function on PHP 5.1.0

<?php// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:date_default_timezone_set('Asia/Tokyo');

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Easterndate_default_timezone_set('US/Eastern');

// Output the date in a standard format (RFC1123), this will print:// Fri, 31 Dec 1999 18:00:00 ESTecho '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?> Question : 33 What is meant by urlencode and urldocode?

Answer : 33 URLencode returns a string in which all non-alphanumeric charactersexcept -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type.

urldecode decodes any %##encoding in the given string.

Question : 34 What is the difference between the functions unlink and unset?

Page 198: PHP HTML CSS  Notes

198

Answer : 34 unlink() deletes the given file from the file system.unset() makes a variable undefined.

Question : 35 How can we register the variables into a session?

Answer : 35 $_SESSION['name'] = "sonia";

Question : 36 How can we get the properties (size, type, width, height) of an image using PHP image functions?

Answer : 36 To know the Image type use exif_imagetype () functionTo know the Image size use getimagesize () functionTo know the image width use imagesx () functionTo know the image height use imagesy() function.

Question : 37 How can we get the browser properties using PHP?

Answer : 37 By using $_SERVER['HTTP_USER_AGENT']variable.

Question : 38 What is the maximum size of a file that can be uploaded using PHP and how can we change this?

Answer : 38 By default the maximum size is 2MB. and we can change the followingsetup at php.ini upload_max_filesize = 2M.

Question : 39 How can we increase the execution time of a PHP script? Answer : 39 by changing the following setup at php.ini max_execution_time = 30; Maximum execution time of each script, in seconds.

Question : 40 How can we take a backup of a MySQL table and how can we restore it. ?

Answer : 40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO'/path/to/backup/directory'. RESTORE TABLE tbl_name[,tbl_name…] FROM '/path/to/backup/directory'mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or

Page 199: PHP HTML CSS  Notes

199

for transferring the data to another SQL server (not necessarily a MySQLserver). The dump will contain SQL statements to create the table and/orpopulate the table.

Question : 41 How can we optimize or increase the speed of a MySQL selectquery?

Answer :

First of all instead of using select * from table1, use selectcolumn1, column2, column3.. from table1

Look for the opportunity to introduce index in the table you arequerying.

Use limit keyword if you are looking for any specific number ofrows from the result set.

Question : 42 How many ways can we get the value of current session id?

Answer : 42 session_id() returns the session id for the current session.    

Question : 43 How can we destroy the session, how can we unset the variable of a session?

Answer : 43 session_unregister to Unregister a global variable from the currentsession session_unset to Free all session variables.

Question : 44 How can we set and destroy the cookie n php?

Answer : 44 By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ;Set the cookies in past for destroy. like setcookie("user", "sonia", time()+3600); for set the cookie setcookie("user", "", time()-3600); for destroy or delete the cookies;

Question : 45 How many ways we can pass the variable through the navigation between the pages?

Page 200: PHP HTML CSS  Notes

200

Answer : 45.

GET/QueryString POST

Question : 46 What is the difference between ereg_replace() and eregi_replace()?Answer : 46 eregi_replace() function is identical to ereg_replace() except thatthis ignores case distinction when matching alphabeticcharacters.eregi_replace() function is identical to ereg_replace()except that this ignores case distinction when matching alphabeticcharacters.

Question : 47 What are the different functions in sorting an array?

Answer : 47 Sort(), arsort(),asort(), ksort(),natsort(), natcasesort(),rsort(), usort(),array_multisort(), and uksort().

Question : 48 How can we know the count/number of elements of an array?

Answer : 48 2 waysa) sizeof($urarray) This function is an alias of count()b) count($urarray)

Question : 49 what is session_set_save_handler in PHP?

Answer : 49 session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.    

Question : 50 How can I know that a variable is a number or not using aJavaScript?

Page 201: PHP HTML CSS  Notes

201

Answer : 50 bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.  

Question : 51 List out some tools through which we can draw E-R diagrams for mysql.

Answer : 51 Case Studio Smart Draw.

Question : 52 How can I retrieve values from one database server and store them in other database server using PHP?

Answer : 52 we can always fetch from one database and rewrite to another. hereis a nice solution of it.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);$db2 = mysql_connect("host","user","pwd")mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);At this point you can only fetch records from you previous ResultSet,i.e $res1 But you cannot execute new query in $db1, even if yousupply the link as because the link was overwritten by the new db.so at this point the following script will fail.$res3 = mysql_query("query",$db1); //this will failSo how to solve that?

take a look below.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);

$db2 = mysql_connect("host","user","pwd", true)mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);

So mysql_connect has another optional boolean parameter whichindicates whether a link will be created or not. as we connect to the$db2 with this optional parameter set to 'true', so both link willremain live.

Page 202: PHP HTML CSS  Notes

202

now the following query will execute successfully.$res3 = mysql_query("query",$db1);

Question : 53 List out the predefined classes in PHP?

Answer : 53 Directory stdClass __PHP_Incomplete_Class exception php_user_filter.

Question : 54 How can I make a script that can be bi-language (supportsEnglish, German)?

Answer : 54 You can maintain two separate language file for each of thelanguage. all the labels are putted in both language files as variablesand assign those variables in the PHP source. on runtime choose therequired language option.    

Question : 55 What are the difference between abstract class and interface?

Answer : 55 Abstract class: abstract classes are the class where one or moremethods are abstract but not necessarily all method has to be abstract.Abstract methods are the methods, which are declare in its class but notdefine. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods areabstract. That means all the methods only declared but not defined. Allthe methods must be define by its implemented class.

Question : 56 How can we send mail using JavaScript?

Answer : 56 JavaScript does not have any networking capabilities as it isdesigned to work on client site. As a result we can not send mails usingJavaScript. But we can call the client side mail protocol mailto

Page 203: PHP HTML CSS  Notes

203

via JavaScript to prompt for an email to send. this requires the clientto approve it.

Question : 57 How can we repair a MySQL table?

Answer : 57 The syntex for repairing a MySQL table isREPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]This command will repair the table specified if the quick is given theMySQL will do a repair of only the index tree if the extended is givenit will create index row by row.

Question : 58 What are the advantages of stored procedures, triggers, indexes?Answer : 58 A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need tokeep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between theserver and the client. You can also raise the conceptual level by havinglibraries of functions in the server. However, stored procedures ofcourse do increase the load on the database server system, as more ofthe work is done on the server side and less on the client (application)side.Triggers will also be implemented. A trigger is effectively a type ofstored procedure, one that is invoked when a particular event occurs.For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that storedprocedure automatically deletes the corresponding customer from acustomer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.Without an index, MySQL must begin with the first row and then readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns inquestion, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If atable has 1,000 rows, this is at least 100 times faster than reading

Page 204: PHP HTML CSS  Notes

204

sequentially. If you need to access most of the rows, it is faster toread sequentially, because this minimizes disk seeks.

Question : 59 What is the maximum length of a table name, database name, and fieldname in MySQL?

Answer : 59 The following table describes the maximum length for each type ofidentifier.

Identifier Maximum Length(bytes)

Database 64

Table 64

Column 64

Index 64

Alias 255

There are some restrictions on the characters that may appear inidentifiers:

Question : 60 How many values can the SET function of MySQL take?

Answer : 60 MySQL set can take zero or more values but at the maximum it cantake 64 values.

Question : 61 What are the other commands to know the structure of table using MySQL commands except explain command?

Answer : 61 describe Table-Name;

Question : 62 How many tables will create when we create table, what are they?Answer : 62 The '.frm' file stores the table definition.

Page 205: PHP HTML CSS  Notes

205

The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension.

Question : 63 What is the purpose of the following files having extensions 1) .frm 2) .myd 3) .myi? What do these files contain?

Answer : 63 In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files have namesthat begin with the table name and have an extension to indicate thefile type.The '.frm' file stores the table definition.The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension.

Question : 64 What is maximum size of a database in MySQL?

Answer : 64 If the operating system or filesystem places a limit on the numberof files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, databaseperformance can be adversely affected. The amount of available disk space limits the number of tables.MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to65536 terabytes (2567 – 1 bytes). With this larger allowed table size,the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB. The following table lists some examples of operating system file-sizelimits. This is only a rough guide and is not intended to be definitive.For the most

Page 206: PHP HTML CSS  Notes

206

up-to-date information, be sure to check the documentationspecific to your operating system.Operating System File-size.

LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB) Linux 2.4+ (using ext3 filesystem) 4TBSolaris 9/10 16TBNetWare w/NSS filesystem 8TBWin32 w/ FAT/FAT32 2GB/4GBWin32 w/ NTFS 2TB (possibly larger)MacOS X w/ HFS+ 2TB.

Question : 65 Give the syntax of Grant and Revoke commands?

Answer : 65 The generic syntax for grant is as following GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY [password] now rights can bea) All privilegesb) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specificdatabase by database.* or a specific table by database.table_nameusername@hotsname can be either username@localhost, username@hostnameand username@%where hostname is any valid hostname and % represents any name, the *.*any conditionpassword is simply the password of userThe generic syntax for revoke is as following

REVOKE [rights] on [database/s] FROM [username@hostname] now rights can be as explained abovea) All privilegesb) combination of create, drop, select, insert, update and delete etc.username@hotsname can be either username@localhost, username@hostnameand username@%where hostname is any valid hostname and % represents any name, the *.*any condition    

Question : 66 Explain Normalization concept?

Page 207: PHP HTML CSS  Notes

207

Answer : 66 The normalization process involves getting our data to conform tothree progressive normal forms, and a higher level of normalizationcannot be achieved until the previous levels have been achieved (thereare actually five normal forms, but the last two are mainly academic andwill not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant datafrom horizontal rows. We want to ensure that there is no duplication ofdata in a given row, and that every column stores the least amount ofinformation possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across ahorizontal row, Second Normal Form (or 2NF) deals with redundancy ofdata in vertical columns. As stated earlier, the normal forms areprogressive, so to achieve Second Normal Form, your tables must alreadybe in First Normal Form.Third Normal Form

I have a confession to make; I do not often use Third Normal Form. InThird Normal Form we are looking for data in our tables that is notfully dependant on the primary key, but dependant on another value inthe table

Question : 67 How can we find the number of rows in a table using MySQL? Answer : 67 Use this for mysql SELECT COUNT(*) FROM table_name;

Question : 68 How can we find the number of rows in a result set using PHP?

Answer : 68 $result = mysql_query($sql, $db_link);$num_rows = mysql_num_rows($result);echo "$num_rows rows found";

Question : 69 How many ways we can we find the current date using MySQL?

Page 208: PHP HTML CSS  Notes

208

Answer : 69 SELECT CURDATE();CURRENT_DATE() = CURDATE()for time useSELECT CURTIME();CURRENT_TIME() = CURTIME()

Question : 70 What are the advantages and disadvantages of Cascading Style Sheets?

Answer : 70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be created for use on multiple HTML element types in many documents. Selector and grouping methods can be used to apply styles under complex contextsDisadvantagesAn extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities ofstyle definitions Embedded Style Sheets Advantages Classes can be created for use on multiple tag types in the document. Selector and grouping methods can be used to apply styles under complex contexts. No additional downloads necessary to receive style information

Disadvantages

This method can not control styles for multiple documents at once

Inline Styles

Advantages

Useful for small quantities of style definitions. Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods.

Disadvantages

Does not distance style information from content (a main goal of SGML/HTML). Can not control styles for multiple documents at once. Author can not create or control classes of elements to control multiple element types within the document. Selector grouping

Page 209: PHP HTML CSS  Notes

209

methods can not be used to create complex element addressing scenarios

Question : 71 What type of inheritance that PHP supports?

Answer : 71 In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not supported. Classes are extended sing the keyword 'extends'.

Question : 72 What is the difference between Primary Key andUnique key?

Answer : 72 Primary Key: A column in a table whose values uniquely identify therows in the table. A primary key value cannot be NULL.

Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be more than one unique for a table.   Question : 73 what is garbage collection? default time ? refresh time?

Answer : 73 Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. Garbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory. There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100.

Question : 74 What are the advantages/disadvantages of MySQL and PHP? Answer : 74 Both of them are open source software (so

Page 210: PHP HTML CSS  Notes

210

free of cost), supportcross platform. php is faster then ASP and JSP.

Question : 75 What is the difference between GROUP BY and ORDER BY in Sql? Answer : 75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value ofcolumn col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, ifyou want to count all items in group, sum all values or view average.

Question : 76 What is the difference between char and varchar data types? Answer : 76 Set char to occupy n bytes and it will take n bytes even if u r storing a value of n-m bytes Set varchar to occupy n bytes and it will take only the required space and will not use the n byteseg. name char(15) will waste 10 bytes if we store 'romharshan', if each chartakes a byteeg. name varchar(15) will just use 5 bytes if we store 'romharshan', if eachchar takes a byte. rest 10 bytes will be free.

Question : 77 What is the functionality of md5 function in PHP?

Answer : 77 Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify users etc. If I add random no techniques to it the md5 generated nowwill be totally different for the same string I am using.

Question : 78 How can I load data from a text file into a table?

Answer : 78 you can use LOAD DATA INFILE file_name; syntax to load data from a text file. but you have to make sure thata) data is delimited b) columns and data matched correctly.

Question : 79 How can we know the number of days between two given dates using MySQL?

Page 211: PHP HTML CSS  Notes

211

Answer : 79 SELECT DATEDIFF("2007-03-07","2005-01-01");

Question : 80 How can we know the number of days between two given dates using PHP?

Answer : 80 $date1 = date("Y-m-d");$date2 = "2006-08-15";$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);

Question : 81 How we load all classes that placed in different directory in one PHP File , means how to do auto load classes.

Answer : 81by using spl_autoload_register('autoloader::funtion');Like below class autoloader

{public static function moduleautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] . "/modules/{$class}.php";

if (is_readable($path)) require $path;

}public static function daoautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] . "/dataobjects/{$class}.php";

if (is_readable($path)) require $path;}

public static function includesautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] . "/includes/{$class}.php";if (is_readable($path)) require $path;

Page 212: PHP HTML CSS  Notes

212

}}spl_autoload_register('autoloader::includesautoloader');spl_autoload_register('autoloader::daoautoloader');spl_autoload_register('autoloader::moduleautoloader');

Question : 82 How many types of Inheritances used in PHP and how we achieve it.

Answer : 82 As far PHP concern it only support single Inheritance in scripting.we can also use interface to achieve multiple inheritance.

Question : 83 PHP how to know user has read the email?

Answer : 83 Using Disposition-Notification-To: in mailheader we can get read receipt.Add the possibility to define a read receipt when sending an email.It’s quite straightforward, just edit email.php, and add this at vars definitions:var $readReceipt = null;And then, at ‘createHeader’ function add:if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }

Question : 84 What are default session time and path?

Answer : 84 default session time in PHP is 1440 seconds or 24 minutesDefault session save path id temporary folder /tmp.

Question : 85 how to track user logged out or not? when user is idle ? Answer : 85 By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes. The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the

Page 213: PHP HTML CSS  Notes

213

session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

Question : 86 how to track no of user logged in ?

Answer : 86 whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.

Question : 87 in PHP for pdf which library used?

Answer : 87 The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

Question : 88 for image work which library?

Answer : 88 we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

Question : 89 what is design pattern? singleton pattern?

Answer : 89 A design pattern is a general reusable solution to a commonly occurring problem in software design. The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

Question : 90 what are magic methods?

Answer : 90 Magic methods are the members functions that is available to all the instance of class Magic methods always starts with "__". Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class

Page 214: PHP HTML CSS  Notes

214

or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone().

Question : 91 what is magic quotes?

Answer : 91 Magic Quotes is a process that automatically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

Question : 92 what is cross site scripting? SQL injection?

Answer : 92 Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts. SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.

Question : 93 what is URL rewriting?

Answer : 93 Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users. along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.    

Question : 94 what is the major php security hole? how to avoid?

Answer : 94 1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval()

Page 215: PHP HTML CSS  Notes

215

function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you don’t want the file contents to be seen, give the file a .php extension.

Question : 95 whether PHP supports Microsoft SQL server ?

Answer : 95 The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.

Question : 96 what is MVC? why its been used?

Answer : 96 Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model. WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:A Tweaking design (HTML) without altering code B Web design staff can modify UI without understanding code.

Question : 97 what is framework? how it works? what is advantage? Answer : 97 In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something

Page 216: PHP HTML CSS  Notes

216

useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance.

Question : 98 what is CURL?

Answer : 98 CURL means Client URL Librarycurl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate), file transfer resume, proxy tunneling and a busload of other useful tricks. CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading. HTTP form based upload, proxies, cookies, and user+password authentication.

Question : 99 what is PDO ?

Answer : 99

The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for accessing databases in PHP. if you are using the PDO API, you could switch the database server you used, from say PgSQL to MySQL, and only need to make minor changes to your PHP code. While PDO has its advantages, such as a clean, simple, portable API but its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.

Just need to use below code for connect mysql using PDOtry {$dbh = new PDO("mysql:host=$hostname;dbname=databasename", $username, $password);$sql = "SELECT * FROM employee";

Page 217: PHP HTML CSS  Notes

217

foreach ($dbh->query($sql) as $row){print $row['employee_name'] .' - '. $row['employee_age'] ;}}catch(PDOException $e){echo $e->getMessage();}    

Question : 100 What is PHP's mysqli Extension ?

Answer : 100The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being: =>Object-oriented interface =>Support for Prepared Statements =>Support for Multiple Statements =>Support for Transactions =>Enhanced debugging capabilities

B.Praveen Kumar(Trainer in PHP)

Sathya Technology,Ameerpet

e-mailid:[email protected]

Student e-mailid:[email protected]