Você está na página 1de 169

aWhat is HTML? HTML is a language for describing web pages.

HTML stands for Hyper Text Markup Language HTML is a markup language HTML is case-insensitive language A markup language is a set of markup tags The tags describe document content HTML documents contain HTML tags and plain text HTML documents are also called web pages HTML Tags HTML markup tags are usually called HTML tags HTML tags are keywords (tag names) surrounded by angle brackets like <html> HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag The end tag is written like the start tag, with a forward slash before the tag name Start and end tags are also called opening tags and closing tags <tagname>content</tagname>

BASIC WEB PAGE STRUCTURE <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> Example Explained The <!DOCTYPE> declaration is supported in all major browsers.

Definition and Usage The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag. The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in. In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language, so that the browsers render the content correctly. Common DOCTYPE Declarations

<!DOCTYPE html> HTML 4.01 Strict This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> HTML 4.01 Transitional This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> HTML 4.01 Frameset This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> XHTML 1.0 Strict This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> XHTML 1.0 Transitional

The text between <html> and </html> describes the web page The text between <body> and </body> is the visible page content The text between <h1> and </h1> is displayed as a heading The text between <p> and </p> is displayed as a paragraph

Web Browsers The purpose of a web browser (such as Google Chrome, Internet Explorer, Firefox, Safari) is to read HTML documents and display them as web pages. The browser does not display the HTML tags, but uses the tags to interpret the content of the page:

Writing HTML Using Notepad or TextEdit HTML can be edited by using a professional HTML editor like: Adobe Dreamweaver Microsoft Expression Web CoffeeCup HTML Editor However, for learning HTML we recommend a text editor like Notepad (PC) or

TextEdit (Mac). We believe using a simple text editor is a good way to learn HTML. Follow the 4 steps below to create your first web page with Notepad. Step 1: Start Notepad To start Notepad go to: Start-> All Programs->Accessories->Notepad Step 2: Edit Your HTML with Notepad Type your HTML code into your Notepad:

Step 3: Save Your HTML Select Save as.. in Notepad's file menu. When you save an HTML file, you can use either the .htm or the .html file extension. There is no difference, it is entirely up to you. Save the file in a folder that is easy to remember, like w3schools. Step 4: Run the HTML in Your Browser Start your web browser and open your html file from the File, Open menu, or just browse the folder and double-click your HTML file. The result should look much like this:

HTML Attributes

HTML elements can have attributes Attributes provide additional information about an element Attributes are always specified in the start tag Attributes come in name/value pairs like: name="value" Attribute Example HTML links are defined with the <a> tag. The link address is specified in the href attribute: <a href="http://www.w3schools.com">This is a link</a>

HTML COMMON TAG LIST Structure Tags <HTML>...</HTML> Opens and closes all HTML documents.

<HEAD>...</HEAD> <TITLE>...</TITLE> <BODY>...</BODY>

Encloses document header. Contains the document's assigned title. Contains the body of the HTML document. Attributes: BGCOLOR=". Sets background colour. .." TEXT="..." LINK="..." VLINK="..." Sets colour of text. Sets colour color of unvisited links. Sets colour of visited links.

Headings <H1>...</H1> <H6>...</H6> Used to set size of headings. Values of 1 through 6; with 1 being the largest, 6 the smallest.

Paragraphs <P>...</P> Links <A>....</A> Creates a link to another document or anchor. Attributes : HREF The URL of a document to which a given document is linked. Denotes an anchor name. Used to denote a plain paragraph.

NAME

TARGET _blank _self _top _parent Lists <OL>...</OL> An ordered (numbered) list.

Attributes type start <UL>...</UL> A,i,I,a integer

An unordered (unnumbered), bulleted list. Attributes type Square,disc,circle A list item.

<LI> Character Formatting <B>...</B> <I>...</I> <U>...</U> Other Elements <!-- -->

Bold text. Italic text. Underlined text.

Comment - creates a comment which is not displayed in browser - found in the <BODY> tag. A horizontal rule. Attributes: SIZE="..." The thickness of a rule in pixels. WIDTH=". The width of the rule in pixels .." or percent. ALIGN=".. Possible values are LEFT, .." RIGHT and CENTER. NOSHAD Causes the rule to be drawn as a E solid black line.

<HR>

<BR>

A line break. Attributes: CLEAR=" Causes text to stop flowing ..." around images - possible values are LEFT, RIGHT and ALL.

<CENTER>...</CENTER> <FONT>...</FONT>

Centers everything between these tags. Changes font size.

Attributes: SIZE="..." Specifies font size from 1-7. Default is 3. COLOR=" Specifies text colour. ..." Images <IMG> Used to place an image into a document. Attributes: SRC="..." ALT="..." Information as to an image's physical location. Alternate text to be displayed should an image be missing, or images are turned off in browser.

ALIGN="... Determines horizontal image " alignment; either LEFT or RIGHT. VALIGN=". Determines vertical image .." alignment; either TOP, MIDDLE, or BOTTOM. WIDTH="... The width in pixels of an " image. HEIGHT=". The height in pixels of the .." image. BORDER=" Creates a border around a ..." linked image. "BORDERCOLOR=" may also be specified.

Tables <TABLE>...</TABLE> Creates a table. Attributes: BORDER="...." Indicates whether a table should have a border.

May also specify a value indicating the width of a border. CELLSPACING Specifies amount of ="..." space between cells in a table. WIDTH="..." Specifies width of a table, either in pixels or as a percentage.

<TR>...</TR> <TD>....</TD>

Defines a table row. Defines a table data cell. **found in a <TR>....</TR>.

Frames <FRAMESET>...</FRAM ESET> The main container for a frame document. Attributes: COLS="... Specifies a frame's column size " in pixels or as a percentage. ROWS=". Specifies a frame's row size in .." pixels or as a percentage. <FRAME> Contains information about a single frame. Attributes: SRC="..." The URL of a document to be displayed in a given frame.

SCROLLING="...." Indicates whether a frame has scroll bars (YES, NO, or AUTO). MARGINHEIGHT Specifies a frame = "...." margin's height in pixels. MARGINWIDTH= Specifies a frame "...." margin's width in pixels. <NOFRAMES>.browser Used to display text when viewed with a non-

do not support </NOFRAMES> OTHER Tags <SUB> <SUP> <ABBR> <ACRONYM> <FIELDSET> <LEGEND> <IFRAME>

frames capable browser.

The <sub> tag defines subscript text like H2O. The <sup> tag defines superscript text like WWW[1]. Defines an abbreviation like WHO Defines an abbreviation like NASA This draws a box around the related elements. The <legend> tag defines a caption for the <fieldset> element. An inline frame is used to embed another document within the current HTML document. <iframe src="http://www.w3schools.com"></iframe> Creates submit,reset or button Attribute's value name Text on button Name of buttons

FORM ELEMENTS <input type = "button", "submit", or "reset">

<input type = "image"> <input type = "text">

Use image as submit button Creating text field Attributes Value Name Default value in text box Name of textbox

<input type = "password"> <input type="checkbox"> <input type="radio"> <select> <textarea>

Creating password field Creating Checkboxes Creating Radio buttons Creating drop down lists Creating Textarea

Example of Text tags <html> <head> <title>Text Tags</title> </head> <body bgcolor="pink" background='images/image1.jpg'> <!-- Text elements and their attributes--> <p>This is an Example of a paragraph</p> <h1>Netmax Technologies</h1> <h2>Netmax Technologies</h2> <h3>Netmax Technologies</h3> <h4>Netmax Technologies</h4> <h5>Netmax Technologies</h5> <h6 align='right'>Netmax Technologies</h6> <!--Moving text--> <marquee direction='down' onmouseover="this.stop()" onmouseout="this.start()" scrollamount="30">Netmax Technologies</marquee> </body> </html> Screenshot Example of Image, links,character formatting tags <html> <head> <title>Html Tags</title> </head> <body>

<!--Character Formatting Tags--> <p><font color="red" size="3" face="arial">Netmax</font></p> <p><i>Welcome</i> <u><b>user</b></u> to our site</p>

<!--Embedding Images--> <img src='images/cisco_logo.png' alt='cisco logo' title='cisco'/>

<!--Empty tags--> <br><hr>

<!--Creating links--> <a href='#'>Link</a> <a href='http://yahoo.com'>Yahoo</a> <a href='home.html'>Home</a> </body> </html>

Example of lists(Ordered list,Unordered List,Defination List) <html> <head> <title>Lists</title> </head> <body> <!--Unordered List--> <ul type="square"> <li>Home</li> <li>Contact us</li>

<li>About us</li> </ul> <!--Ordered List--> <ol type="I" start="3"> <li>Home</li> <li>Contact us</li> <li>About us</li> </ol> <!--Defination List--> <dl> <dt>PHP</dt> <dd>php is scripting language to bulid sites</dd> <dt>AsP.net</dt> <dd>in asp.net we can create websites</dd> </dl> </body> </html> Example of Iframes,other tags <html> <head> <title>Tags in html</title> </head> <body> <!--iFrame--> <iframe src='http://w3schools.com' width='400px' height='500px'> </iframe> <!--others-->

<p>H<sub>2</sub>O</p> <p>www<sup>[1]</sup></p> <center><img src='images/cisco_logo.png'/></center> <pre>This <!--Cr--> </body> </html> Example of creating forms <html> <head> <title>Form elements</title> </head> <body> <fieldset> <legend>Application form</legend> <form action="a.html" method="post"> Username<input type="text" name="user" value="enter name" size="40"/> <label>Password</label><input type="password" name="pass" value="123" readonly="true"/> <label>Gender</label> <input type="radio" name="gen" value="m">Male</input> <input type="radio" name="gen" value="f">Female</input> <label>Hobbies</label> <input type="checkbox">Music</input> <input type="checkbox">Arts</input><br> Message <textarea rows="10" cols="40">enter msg here</textarea> Countries<select name="cn" multiple="multiple"> <option value='ind'>India</option> is a paragraph</pre>

<option value='usa'>USA</option> <option value='aus'>Australia</option> </select> <input type="submit" value="create account"/> <input type="button" value="go to next"/> <input type="reset"/> <button>Click</button> </form> </fieldset> </body> </html> Example of Image map <html> <body> <p>Click on the sun or on one of the planets to watch it closer:</p> <img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap" /> <map name="planetmap"> <area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.html" /> <area shape="circle" coords="124,58,8" alt="Venus" href="mercury.html" /> <area shape="poly" coords="90,80,135,100,140,80" alt="" href="venus.html"/> </map> </body> </html> Example of Frames <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd"> <frameset rows="25%,75%" border="20" framespacing="30"> <frame src="newtest.html" ></frames> <frameset cols="25%,75%" bordercolor="red"> <frame src="links.html" marginheight="60px" scrolling="no" noresize marginwidth="20" marginheight="0px"></frames> <frame src="ccna.html" name="rightwindow"> </frame> </frameset> <!--links.html--> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> </head> <body> <a href="ccna.html" target="rightwindow" >CCNA</a><br> <a href="mcse.html" target="rightwindow">MCSE</a><br> <a href="java.html" target="_parent">JAVA</a><br>

</body> </html> Example of tables

<html> <head> <title>Creating Tables</title> </head> <body> <table border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> </body> </html> Example of table with Nested Tables with Rowspan and colspan <html> <body> <table border="2" width="100%" height="100%" cellpadding="13px" cellspacing="10px" bordercolor="green"> <tr> <th colspan="2">Students Information</th> </tr> <tr> <td rowspan="2">name</td> <td> <table border="1" width="100%" height="100%"> <tr bgcolor="red"><td>first</td><td>second</td></tr> </table>

</td> </tr> <tr> <td>Aman</td> </tr> </table> </body> </html>

CSS:Cascading Style Sheets

What is CSS? CSS stands for Cascading Style Sheets Styles define how to display HTML elements Styles are normally stored in Style Sheets Styles were added to HTML 4.0 to solve a problem Style Sheets can save you a lot of work CSS contain properties applied on different tags

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. The property is the style attribute you want to change. Each property has a value. For each selector there are 'properties' inside curly brackets, which simply take the form of words such as color, font-weight or background-color. A value is given to the property following a colon (NOT an 'equals' sign) and semi-colons separate the properties.

Types of Stylesheets 1.Inline Stylesheetapplied on one tag at a time 2.Internal Stylesheet---applied on one page 3.External Stylesheet---applied on multiple webpages In-line In-line styles are used straight into the HTML tags using the style attribute. They look something like this: Syntax:
<p style=color:red>Text</p>

This will make that specific paragraph red. The approach of HTML Document is that the HTML should be a standalone,presentation free document, and so in-line styles should be avoided wherever possible. Internal Internal styles are used for the whole page. Inside the head tags, the style tag surrounds all of the styles for the page. This would look something like this: Syntax: <html> <head> <title>CSS Example</title> <style type="text/css"> </head>
p {color: red;} </style>

<body> <p>hello world!</p> </html> This will make all of the paragraphs in the page red and all of the links blue. External External styles are used for the whole, multiple-page website. There is a separate CSS file, which will simply look something like: Syntax:
p { color:red; } a { color: blue; }

If this file is saved as 'web.css' then it can be linked to in the HTML like this: <html> <head> <title>CSS Example</title> <link rel="stylesheet" type="text/css" href="web.css" /> </head> <body> <p>This is demo </p> <a href='#'>Home</a> </body> </html>

Syntax:

Grouping You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. All header elements will be displayed in green text color: Syntax h1,h2,h3,h4,h5,h6 { color: green }

Id and class Attribute's/Selectors In addition to setting a style for a HTML element, CSS allows you to specify your own selectors called "id" and "class".

The 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":

Example: #para1 { text-align:center; color:red; } Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.

The 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 a "." In the example below, all HTML elements with class="center" will be center-aligned: Example: .center {text-align:center;} p.center {text-align:center;} You can also specify that only specific HTML elements should be affected by a class. Example: p.center {text-align:center;} Do NOT start a class name with a number! This is only supported in Internet Explorer . Example of id and class selectors

<html> <head> <title>Id and Class</title> <style type="text/css"> #para1 { color:red; font-size:22; } .second { color:blue; font-size:44; } </style> </head> <body> <p id="para1">This is text</p> <h2>This is an example of css</h2> <p class="second">This is text</p> <h2 class="second">This is an example of css</h2> <p>This is text</p> <h2>This is an example of css</h2> </body> </html> CSS Comments Comments are used to explain your code, and may help you when you edit the source code at a later date. A comment will be ignored by browsers. A CSS comment begins with "/*", and ends with "*/", like this /* This is a comment */ p { text-align: center; /* This is another comment */ color: black; font-family: arial } CSS Background Properties

The CSS background properties allow you to control the background color of an element, set an image as the background, repeat a background image vertically or horizontally, and position an image on a page.

Property background

Description A shorthand property for setting all background properties in one declaration Sets whether a background image is fixed or scrolls with the rest of the page Sets the background color of an element

Values background-color background-image background-repeat background-attachment background-position scroll fixed

backgroundattachment

background-color

color-rgb color-hex color-name transparent url none

background-image

Sets an image as the background

background-position Sets the starting position top left of a background image top center top right center left center center center right bottom left bottom center bottom right x-% y-% x-pos y-pos background-repeat Sets if/how a background image will be repeated repeat repeat-x repeat-y no-repeat

Example: <html> <head> <style type="text/css"> body { background:#ffffff ; background-image:url('img_tree.png') background-repeat:no-repeat; background-position: right top;

background-attachment:fixed; } </style> </head> <body> <h1>Hello World!</h1> <p>Now the background image is only shown once, and it is also positioned away from the text.</p> </body> </html> CSS Text Properties The CSS text properties define the appearance of text. CSS Text Properties The CSS text properties allow you to control the appearance of text. It is possible to change the color of a text, increase or decrease the space between characters in a text, align a text, decorate a text, indent the first line in a text, and more. Property color direction letter-spacing Description Values

Sets the color of a text color Sets the text direction ltr rtl Increase or decrease the space between characters Aligns the text in an element normal length left right center justify none underline overline line-through blink length %

text-align

text-decoration

Adds decoration to text

text-indent

Indents the first line of text in an element

text-transform

Controls the letters in none an element capitalize uppercase lowercase Sets how white space normal inside an element is pre handled nowrap Increase or decrease the space between words normal length

white-space

word-spacing

CSS Font Properties The CSS font properties define the font in text. CSS Font Properties The CSS font properties allow you to change the font family, boldness, size, and the style of a text. Note: In CSS1 fonts are identified by a font name. If a browser does not support the specified font, it will use a default font. Browser support: IE: Internet Explorer, F: Firefox, N: Netscape. W3C: The number in the "W3C" column indicates in which CSS recommendation the property is defined (CSS1 or CSS2). Property Description Values font A shorthand property for setting all of the properties for a font in one declaration font-style font-variant font-weight font-size/line-height font-family caption icon menu message-box small-caption status-bar

font-family

A prioritized list of family-name font family names generic-family and/or generic family names for an element Sets the size of a font xx-small x-small

font-size

small medium large x-large xx-large smaller larger length % font-stretch Condenses or expands normal the current fontwider family narrower ultra-condensed extra-condensed condensed semi-condensed semi-expanded expanded extra-expanded ultra-expanded Sets the style of the font Displays text in a small-caps font or a normal font Sets the weight of a font normal italic oblique normal small-caps normal bold bolder lighter 100 200 300 400 500 600 700 800 900

font-style

font-variant

font-weight

Example of font and text Properties

<html> <head> <style type="text/css"> p { font-size:22; color:red; font-style:italic; font-weight:bold; font-family:arial; text-align:center; text-decoration:underline; text-transfor:uppercase; } </style> </head> <body> <p> This Paragraph is changed using css properties </p> </body> </html>
CSS List properties

In HTML, there are two types of lists: unordered lists - the list items are marked with bullets ordered lists - the list items are marked with numbers or letters The CSS list properties allow you to place the list-item marker, change between different list-item markers, or set an image as the list-item marker. CSS List Properties The CSS list properties allow you to place the list-item marker, change between different list-item markers, or set an image as the list-item marker.

Property list-style

Description

Values

A shorthand property for list-style-type setting all of the list-style-position

properties for a list in one declaration list-style-image list-style-position Sets an image as the list-item marker Sets where the list-item marker is placed in the list

list-style-image none url inside outside

list-style-type

Sets the type of the list- none item marker disc circle square decimal decimal-leading-zero lower-roman upper-roman lower-alpha upper-alpha lower-greek lower-latin upper-latin hebrew armenian

Example of list List properties <html> <head> <style type="text/css"> ol li { list-style-type:upper-alpha; list-style-position:inside; } </style> </head> <body> <ul> <li>Home</li> <li>Contact Us </li> <li>About</li> </ul> </body> </html>

All list properties in one declaration <html> <head> <style type="text/css"> ul { list-style: square inside url('arrow.gif') } </style> </head> <body> <ul> <li>Home</li> <li>Contact Us </li> <li>About</li> </ul> </body> </html> CSS Pseudo-classes CSS pseudo-classes are used to add special effects to some selectors. Syntax The syntax of pseudo-classes: selector:pseudo-class {property: value} CSS classes can also be used with pseudo-classes: selector.class:pseudo-class {property: value} Anchor Pseudo-classes A link that is active, visited, unvisited, or when you mouse over a link can all be displayed in different ways in a CSS-supporting browser: a:link {color: #FF0000} /* unvisited link */ a:visited {color: #00FF00} /* visited link */ a:hover {color: #FF00FF} /* mouse over link */ a:active {color: #0000FF} /* selected link */ Note: a:hover MUST come after a:link and a:visited in the CSS definition in order

to be effective!! Note: a:active MUST come after a:hover in the CSS definition in order to be effective!! Note: Pseudo-class names are not case-sensitive. Pseudo-classes and CSS Classes Pseudo-classes can be combined with CSS classes: a.red:visited {color: #FF0000} <a class="red" href="css_syntax.asp">CSS Syntax</a> If the link in the example above has been visited, it will be displayed in red. Example of link Properties <!--Link properties in css--> <html> <head> <style type="text/css"> a#top:link { color:red; font-size:22; text-decoration:none; } a#top:visited { color:green; font-size:22; text-decoration:none; } a#top:hover { color:blue; font-size:22; text-decoration:none; } a#top:active { color:pink; font-size:22; text-decoration:none; }

</style> </head> <body> <h1>Netmax Technologies</h1> <ul> <li>Home</li> <li>Contact us </li> <li>About us</li> </ul> <a href="#" id="top">Java</a> <a href="#" id="top">PHP</a> <p>copyright</p> <h1>Footer area</h1> <a href='#'>CCNA</a> <a href='#'>CCIE</a> </body> </html>

CSS Display Properties Block and Inline Elements A block element is an element that takes up the full width available, and has a line break before and after it. Examples of block elements:
<h1> <p> <div>

An inline element only takes up as much width as necessary, and does not force line breaks. Examples of inline elements: <span> <a> Changing How an Element is Displayed Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow web standards. The following example displays list items as inline elements: <!DOCTYPE html>

<html> <head> <style> li{ display:inline; } a { display:block; } </style> </head> <body> <p>Display this link list as a horizontal menu:</p> <ul> <li></li> <li>CSS</a></li> <li>JavaScript</li> <li>XML</li> </ul> <a href="css.html" target="_blank">CSS</a> <a href="java.html" target="_blank">Java</a> </body> </html> Hiding an Element - display:none or visibility:hidden Hiding an element can be done by setting the display property to "none" or the visibility property to "hidden". However, notice that these two methods produce different results: visibility:hidden hides an element, but it will still take up the same space as before. The element will be hidden, but still affect the layout.<!DOCTYPE html> <html> <head>

<style> #test1{ display:none; } a#one { visibility:hidden; } </style> </head> <body> <p>Display this link list as a horizontal menu:</p> <ul> <li></li> <li>CSS</a></li> <li id=test1>JavaScript</li> <li>XML</li> </ul> <a href="css.html" target="_blank" id=one>CSS</a> <a href="java.html" target="_blank">Java</a> </body> </html>

CSS Border Properties The CSS border properties define the borders around an element. CSS Border Properties The CSS border properties allow you to specify the style and color of an element's border. In HTML we use tables to create borders around a text, but with the CSS border properties we can create borders with nice effects, and it can be applied to any element.

Property

Description

Values

border

A shorthand property border-width for setting all of the border-style properties for the four border-color borders in one declaration A shorthand property border-bottom-width for setting all of the border-style properties for the border-color bottom border in one declaration Sets the color of the bottom border Sets the style of the bottom border Sets the width of the bottom border border-color border-style thin medium thick length

border-bottom

border-bottomcolor border-bottomstyle border-bottomwidth

border-color

Sets the color of the color four borders, can have from one to four colors A shorthand property border-left-width for setting all of the border-style properties for the left border-color border in one declaration Sets the color of the left border Sets the style of the left border border-color border-style thin medium thick length

border-left

border-left-color border-left-style

border-left-width Sets the width of the left border

border-right

A shorthand property border-right-width for setting all of the border-style properties for the right border-color border in one declaration border-color

border-right-color Sets the color of the

right border border-right-style Sets the style of the right border border-right-width Sets the width of the right border border-style thin medium thick length none hidden dotted dashed solid double groove ridge inset outset

border-style

Sets the style of the four borders, can have from one to four styles

border-top

A shorthand property border-top-width for setting all of the border-style properties for the top border-color border in one declaration Sets the color of the top border Sets the style of the top border border-color border-style thin medium thick length thin medium thick length

border-top-color border-top-style

border-top-width Sets the width of the top border

border-width

A shorthand property for setting the width of the four borders in one declaration, can have from one to four values

Example of Border properties <html> <head>

<style type="text/css"> table { width:100%; height:100%; border-left-style:dashed; border-left-color:red; border-left-width:3px; border:2px solid red; border-left:3px dashed green; border-collapse:collapse; } tr,td { border:2px dotted blue; } </style> </head> <body> <table> <tr> <td>Cell1</td> <td>Cell2</td> </tr> <tr> <td>cell3</td> <td>cell4</td> </tr> </table> </body> </html> CSS Margin Properties The CSS margin properties define the space around elements. CSS Margin Properties The CSS margin properties define the space around elements. It is possible to use negative values to overlap content. The top, right, bottom, and left margin can be changed independently using separate properties. A shorthand margin property can also be used to change all of the margins at once.

Property margin

Description A shorthand property for setting the margin properties in one declaration

Values margin-top margin-right margin-bottom margin-left

margin-bottom

Sets the bottom auto margin of an element length % Sets the left margin of auto an element length % Sets the right margin of an element auto length %

margin-left

margin-right

margin-top

Sets the top margin of auto an element length %

CSS Padding Properties The CSS padding properties define the space between the element border and the element content. CSS Padding Properties The CSS padding properties define the space between the element border and the element content. Negative values are not allowed. The top, right, bottom, and left padding can be changed independently using separate properties. A shorthand padding property is also created to control multiple sides at once.

Property padding

Description A shorthand property for setting all of the padding properties in one declaration

Values padding-top padding-right padding-bottom padding-left

padding-bottom

Sets the bottom length padding of an element %

padding-left padding-right padding-top

Sets the left padding of an element

length %

Sets the right padding length of an element % Sets the top padding of an element length %

CSS Classification Properties

The CSS classification properties allow you to specify how and where to display an element. CSS Classification Properties The CSS classification properties allow you to control how to display an element, set where an image will appear in another element, position an element relative to its normal position, position an element using an absolute value, and how to control the visibility of an element.

Property clear

Description Sets the sides of an element where other floating elements are not allowed

Values left right both none

cursor

Specifies the type of url cursor to be displayed auto crosshair default pointer move e-resize ne-resize nw-resize n-resize se-resize sw-resize s-resize w-resize text wait help

float

Sets where an image left or a text will appear in right another element none Example of margin,padding and float <html> <head> <style type="text/css"> #header { width:100%;height:800px; background-color:red; } #left { width:300px; height:150px; background-color:yellow; margin-left:10px; float:left; } #right { width:300px; height:150px; background-color:blue; float:left; margin-left:30px; } </style> </head> <body> <div id="header"> <div id="left"> </div> <div id="right"> </div> </div> </body>

</html>

CSS Positioning Properties The CSS positioning properties allows you to position an element. CSS Positioning Properties The CSS positioning properties allow you to specify the left, right, top, and bottom position of an element. It also allows you to set the shape of an element, place an element behind another, and to specify what should happen when an element's content is too big to fit in a specified area.

Property bottom

Description Sets how far the bottom edge of an element is above/below the bottom edge of the parent element

Values auto % length

left

Sets how far the left auto edge of an element is % to the right/left of the length left edge of the parent element Sets what happens if the content of an element overflow its area Places an element in a static, relative, absolute or fixed position visible hidden scroll auto static relative absolute fixed

overflow

position

right

Sets how far the right auto edge of an element is % to the left/right of the length right edge of the parent element Sets how far the top auto

top

edge of an element is % above/below the top length edge of the parent element vertical-align Sets the vertical alignment of an element baseline sub super top text-top middle bottom text-bottom length %

z-index

Sets the stack order of auto an element number

static

absolute

fixed relative

Default. Elements render in order, as they appear in the document flow The element is positioned relative to its first positioned (not static) ancestor element The element is positioned relative to the browser window The element is positioned relative to

inherit

its normal position, so "left:20" adds 20 pixels to the element's LEFT position The value of the position property is inherited from the parent element

Example of Relative Position <html> <head> <title>Css positioning</title> <style type="text/css"> #header { width:200px; height:200px; background-color:red; } #main { width:200px; height:200px; background-color:yellow; position:relative; top:0px;left:50px; } #left { width:100px; height:100px; background-color:green; position:absolute; left:30px;top:20px; } </style> <body> <div id="header"> </div> <div id="main"> <div id="left"> </div> <div id="right">

</div> </div> </body> </html> Example of Absolute Position <html> <head> <title>Css positioning</title> <style type="text/css"> #header { width:200px; height:200px; background-color:red; } #main { width:200px; height:200px; background-color:yellow; position:absolute; top:0px;left:50px; } #left { width:100px; height:100px; background-color:green; position:absolute; left:30px;top:20px; } </style> <body> <div id="header"> </div> <div id="main"> <div id="left"> </div> <div id="right"> </div> </div>

</body> </html> Example of Fixed Position and Relative Position together <html> <head> <title>Css positioning</title> <style type="text/css"> #header { width:200px; height:200px; background-color:red; } #main { width:200px; height:200px; background-color:yellow; position:relative; } #left { width:100px; height:100px; background-color:green; position:fixed; left:30px;top:20px; } </style> <body> <div id="header"> </div> <div id="main"> <div id="left"> </div> <div id="right"> </div> </div> </body> </html>

Example of Absolute Position and Relative Position together <html> <head> <title>Css positioning</title> <style type="text/css"> #header { width:200px; height:200px; background-color:red; } #main { width:200px; height:200px; background-color:yellow; position:relative; } #left { width:100px; height:100px; background-color:green; position:absolute; left:30px;top:20px; } </style> <body> <div id="header"> </div> <div id="main"> <div id="left"> </div> <div id="right"> </div> </div> </body> </html>

JAVASCRIPT
By definition, JavaScript is a client-side scripting language. This means the web surfer's browser will be running the script. The opposite of client-side is server-side, which occurs in a language like PHP. PHP scripts are run by the web hosting server. JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera. Introduction to JavaScript JavaScript is a scripting language - a scripting language is a lightweight programming

language JavaScript was designed to add interactivity to HTML pages A JavaScript is lines of executable computer code A JavaScript is usually embedded directly in HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license JavaScript is case sensitive Language. Javascript can be used to create Sliders Drop down menus Form Validations

2. How to Put a JavaScript Into an HTML Page <html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> Hello World! Ending Statements With a Semicolon? With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon. Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line. How to Handle Older Browsers Tell the browser where script code ends

Tell the browser where script code begins

The code above will produce this output on an HTML page:

Browsers that do not support JavaScript will display the script as page content. To prevent them from doing this, we may use the HTML comment tag: <script type="text/javascript"> <!-document.write("Hello World!") //--> </script> The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line. 3. Where to Put the JavaScript? Scripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. <html> <head> <script type="text/javascript"> some statements </script> </head>

Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page. <html> <head> </head> <body> <script type="text/javascript"> some statements </script> </body>

Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section. <html> <head> <script type="text/javascript"> some statements </script> </head> <body> <script type="text/javascript"> some statements </script> </body>

Define Variables A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value. Rules for Variable names: Variable names are case sensitive They must begin with a letter or the underscore character

How to declare a Variable? You can create a variable with the var statement: var strname = some value You can also create a variable without the var statement: strname = some value How to Assign a Value to a Variable? You assign a value to a variable like this: var strname = "Tom"

Or like this: strname = "Tom" The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. So far, youve seen examples of variable values that are strings. In JavaScript, the variable values, or types, can include number, string, Boolean, and null. Unlike stricter programming languages, JavaScript does not force you to declare the type of variable when you define it. Instead, JavaScript allows virtually any value to be assigned to any variable. JAVASCRIPT OPERATORS Arithmetic Operators Operator + * / % ++ -Description Addition Example x=2 x+2 Subtraction x=2 5-x Multiplication x=4 x*5 Division 15/5 5/2 Modulus (division 5%2 remainder) 10%8 10%2 Increment x=5 x++ Decrement x=5 x-Result 4 3 20 3 2.5 1 2 0 x=6 X=4

Assignment operators

Operator = +=

Example x=y x+=y

Is The Same As x=y x=x+y

-= *= /= %=

x-=y x*=y x/=y x%=y

x=x-y x=x*y x=x/y x=x%y

Comparison Operators

Operator == != > < >= <=

Description Example is equal to 5==8 returns false is not equal 5!=8 returns true is greater than 5>8 returns false is less than 5<8 returns true is greater than or equal to 5>=8 returns false is less than or equal to 5<=8 returns true

Logical Operators in javascript.

Operator &&

Description and

Example x=6 y=3 (x < 10 && y > 1) returns true

||

or

x=6 y=3 (x==5 || y==5) returns false

not

x=6 y=3 !(x==y) returns true

Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based

on some condition. Syntax variablename=(condition)?value1:value2 Example greeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting.

String Operator in Javascript. A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator. txt1="What a very" txt2="nice day!" txt3=txt1+txt2 The variable txt3 now contains "What a verynice day!". To add a space between two string variables, insert a space into the expression, OR in one of the strings. txt1="What a very" txt2="nice day!" txt3=txt1+" "+txt2 or txt1="What a very " txt2="nice day!" txt3=txt1+txt2 The variable txt3 now contains "What a very nice day!". Types of Javascript's 1.Internal JavaScript----works on one page 2.External Javascript-----can be used on multiple pages Using an External JavaScript Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page. To simplify this, you can write a JavaScript in an external file. Save the external

JavaScript file with a .js file extension. Note: The external script cannot contain the <script> tag! To use the external script, point to the .js file in the "src" attribute of the <script> tag: <html> <head> <script type=text/javascript src="xxx.js"></script> </head> <body> </body> </html> Note: Remember to place the script exactly where you normally would write the script!

JavaScript Date Today (Current) To warm up our JavaScript Date object skills, let's do something easy. If you do not supply any arguments to the Date constructor (this makes the Date object) then it will create a Date object based on the visitor's internal clock. HTML & JavaScript Code: <h4>It is now <script type="text/javascript"> <!-var currentTime = new Date() //--> </script> </h4> Display: It is now Nothing shows up! That's because we still don't know the methods of the Date object that let us get the information we need (i.e. Day, Month, Hour, etc). Get the JavaScript Time The Date object has been created, and now we have a variable that holds the current date! To get the information we need to print out, we have to utilize some or all of the following functions: getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM getSeconds() - Number of seconds (0-59)

getMinutes() - Number of minutes (0-59) getHours() - Number of hours (0-23) getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday getDate() - Day of the month (0-31) getMonth() - Number of month (0-11) getFullYear() - The four digit year (1970-9999) Now we can print out the date information. We will be using the getDate, getMonth, and getFullYear methods in this example. HTML & JavaScript Code: <h4>It is now <script type="text/javascript"> <!-var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() document.write(month + "/" + day + "/" + year) //--> </script> </h4> Display: It is now 1/5/2012 ! Notice that we added 1 to the month variable to correct the problem with January being 0 and December being 11. After adding 1, January will be 1, and December will be 12. Conditional Statements Conditional statements in JavaScript are used to perform different actions based on different conditions.

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: if statement - use this statement if you want to execute some code only if a specified condition is true if...else statement - use this statement if you want to execute some code if the

condition is true and another code if the condition is false if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed switch statement - use this statement if you want to select one of many blocks of code to be executed If Statement You should use the if statement if you want to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if condition is true } Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error! Example 1 <script type="text/javascript"> //Write a "Good morning" greeting if //the time is less than 10 var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script>

Example 2 <script type="text/javascript"> //Write "Lunch-time!" if the time is 11 var d=new Date() var time=d.getHours() if (time==11) {

document.write("<b>Lunch-time!</b>") } </script> Note: When comparing variables you must always use two equals signs next to each other (==)! Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the specified condition is true. If...else Statement If you want to execute some code if a condition is true and another code if the condition is not true, use the if....else statement. Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }

Example <script type="text/javascript"> //If the time is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date() var time = d.getHours() if (time < 10) {

document.write("Good morning!") } else { document.write("Good day!") } </script>

If...else if...else Statement You should use the if....else if...else statement if you want to select one of many sets of lines to execute. Syntax if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true }

Example <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time<10) { document.write("<b>Good morning</b>") } else if (time>10 && time<16) { document.write("<b>Good day</b>")

} else { document.write("<b>Hello World!</b>") } </script> Conditional statements in JavaScript are used to perform different actions based on different conditions. The JavaScript Switch Statement You should use the switch statement if you want to select one of many blocks of code to be executed. Syntax switch(n) { case 1: execute code block 1 break case 2: execute code block 2 break default: code to be executed if n is different from case 1 and 2 } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Example <script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { case 5:

document.write("Finally Friday") break case 6: document.write("Super Saturday") break case 0: document.write("Sleepy Sunday") break default: document.write("I'm looking forward to this weekend!") } </script> JavaScript For Loop Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. JavaScript Loops Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true The for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed } Example Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any

comparing statement. <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 JavaScript While Loop Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. The while loop The while loop is used when you want the loop to execute and continue executing while the specified condition is true. while (var<=endvalue) { code to be executed } Note: The <= could be any comparing statement. Example Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time

the loop runs. <html> <body> <script type="text/javascript"> var i=0 while (i<=10) { document.write("The number is " + i) document.write("<br />") i=i+1 } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 The do...while Loop The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed once, even if the condition is false, because the code is executed before the condition is tested. do { code to be executed } while (var<=endvalue) Example <html> <body> <script type="text/javascript"> var i=0

do { document.write("The number is " + i) document.write("<br />") i=i+1 } while (i<0) </script> </body> </html> Result The number is 0 JavaScript Break and Continue JavaScript break and continue Statements There are two special statements that can be used inside loops: break and continue. Break The break command will break the loop and continue executing the code that follows after the loop (if any). Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3){break} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 Continue

The continue command will break the current loop and continue with the next value. Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3){continue} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 JavaScript Array An array is a variable that can store many variables within it. Many programmers have seen arrays in other languages, and they aren't that different in JavaScript. The following points should always be remembered when using arrays in JavaScript: The array is a special type of variable. Values are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets. Example: myArray[2] = "Hello World"; Values in an array are accessed by the array name and location of the value. Example: myArray[2]; JavaScript has built-in functions for arrays, so check out these built-in array functions before writing the code yourself! JavaScript Code:

<script type="text/javascript"> <!-var myArray = new Array(); myArray[0] = "Football"; myArray[1] = "Baseball"; myArray[2] = "Cricket"; document.write(myArray[0] + myArray[1] + myArray[2]); //--> </script> Display: FootballBaseballCricket JavaScript Code: <script type="text/javascript"> <!-var myArray2= new Array(); myArray2[0] = "Football"; myArray2[1] = "Baseball"; myArray2[2] = "Cricket"; myArray2.sort(); document.write(myArray2[0] + myArray2[1] + myArray2[2]); //--> </script> Display: BaseballCricketFootball

What is Functions? A function contains some code that will be executed by an event or a call to that function. A function is a set of statements. You can reuse functions within the same script, or in other documents. You define functions at the beginning of a file (in the head section), and call them later in the document. It is now time to take a lesson about the alert-box:

This is JavaScript's method to alert the user. Alert("This is a message")

13. How to Define a Function To create a function you define its name, any values ("arguments"), and some statements: function myfunction(argument1,argument2,etc) { some statements }

A function with no arguments must include the parentheses: function myfunction() { some statements } Arguments are variables used in the function. The variable values are values passed on by the function call. By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called. Some functions return a value to the calling expression function result(a,b) { c=a+b return c } 14. How to Call a Function? A function is not executed before it is called. You can call a function containing arguments: myfunction(argument1,argument2,etc) or without arguments:

myfunction()

The return Statement Functions that will return a result must use the "return" statement. This statement specifies the value which will be returned to where the function was called from. Say you have a function that returns the sum of two numbers:

function total(a,b) { result=a+b return result } When you call this function you must send two arguments with it: sum=total(2,3) The returned value from the function (5) will be stored in the variable called sum.

JavaScript Popup Boxes In JavaScript we can create three kind of popup boxes: Alert box, Confirm box, and Prompt box. Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax: alert("sometext") Example: <html> <head> <script type="text/javascript"> function show_alert()

{ alert("I am an alert box!"); } </script> </head> <body> <input type="button" onclick="show_alert()" value="Show alert box" /> </body> </html> Confirm Box A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax: confirm("sometext") Example: <html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Press a button"); if (r==true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" />

</body> </html> Prompt Box A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax: prompt("sometext","defaultvalue") Example: <html> <head> <script type="text/javascript"> function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body> <input type="button" onclick="show_prompt()" value="Show prompt box" /> </body> </html> Setting Date in javascript The setDate() method sets the day of the month to the date object. Syntax

Date.setDate(day) Example <!DOCTYPE html> <html> <body> <script> var d = new Date(); var x=d.setDate(14); document.write(x); } </script> </body> </html> JavaScript Events Events are actions that can be detected by JavaScript. Events By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events: A mouse click A web page or an image loading Mousing over a hot spot on the web page

Selecting an input box in an HTML form Submitting an HTML form A keystroke The following table lists the events recognized by JavaScript: Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! onload and onUnload The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">;

onSubmit The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"> <img src="sch.gif" width="100" height="30"> </a> JavaScript Special Characters In JavaScript you can add special characters to a text string by using the backslash sign. Insert Special Characters The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string. Look at the following JavaScript code: var txt="We are the so-called "Vikings" from the north." document.write(txt) In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal: var txt="We are the so-called \"Vikings\" from the north." document.write(txt) JavasScript will now output the proper text string: We are the so-called "Vikings" from the north. Here is another example: document.write ("You \& me are singing!") The example above will produce the following output: You & me are singing! The table below lists other special characters that can be added to a text string with the backslash sign:

Code \' \" \& \\ \n \r \t \b \f JavaScript Guidelines

Outputs single quote double quote ampersand backslash new line carriage return tab backspace form feed

Some other important things to know when scripting with JavaScript. JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar". JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables, objects and functions. White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: name="Hege" name = "Hege"

Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello \ World!") However, you cannot break up a code line like this: document.write \ ("Hello World!")

Comments You can add comments to your script by using two slashes //: //this is a comment document.write("Hello World!") or by using /* and */ (this creates a multi-line comment block): /* This is a comment block. It contains several lines */ document.write("Hello World!") JavaScript Objects Introduction JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. Object Oriented Programming JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail. Note that an object is just a special kind of data. An object has properties and methods. Properties Properties are the values associated with an object. In the following example we are using the length property of the String object to return the number of characters in a string: <script type="text/javascript"> var txt="Hello World!" document.write(txt.length) </script> The output of the code above will be: 12

Methods Methods are the actions that can be performed on objects. In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: <script type="text/javascript"> var str="Hello world!" document.write(str.toUpperCase()) </script> The output of the code above will be: HELLO WORLD! JavaScript String Object The String object is used to manipulate a stored piece of text. String object The String object is used to manipulate a stored piece of text. Examples of use: The following example uses the length property of the String object to find the length of a string: var txt="Hello world!" document.write(txt.length) The code above will result in the following output: 12 The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters: var txt="Hello world!" document.write(txt.toUpperCase()) The code above will result in the following output: HELLO WORLD!

JavaScript Date Object The Date object is used to work with dates and times. Defining Dates

The Date object is used to work with dates and times. We define a Date object with the new keyword. The following code line defines a Date object called myDate: var myDate=new Date() Note: The Date object will automatically hold the current date and time as its initial value! Manipulate Dates We can easily manipulate the date by using the methods available for the Date object. In the example below we set a Date object to a specific date (14th January 2010): var myDate=new Date() myDate.setFullYear(2010,0,14) And in the following example we set a Date object to be 5 days into the future: var myDate=new Date() myDate.setDate(myDate.getDate()+5) Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself! Comparing Dates The Date object is also used to compare two dates. The following example compares today's date with the 14th January 2010: var myDate=new Date() myDate.setFullYear(2010,0,14) var today = new Date() if (myDate>today) alert("Today is before 14th January 2010") else alert("Today is after 14th January 2010")

JavaScript Array Object The Array object is used to store a set of values in a single variable name. Defining Arrays The Array object is used to store a set of values in a single variable name.

We define an Array object with the new keyword. The following code line defines an Array object called myArray: var myArray=new Array() There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require). 1: var mycars=new Array() mycars[0]="Saab" mycars[1]="Volvo" mycars[2]="BMW" You could also pass an integer argument to control the array's size: var mycars=new Array(3) mycars[0]="Saab" mycars[1]="Volvo" mycars[2]="BMW" 2: var mycars=new Array("Saab","Volvo","BMW") Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string. Accessing Arrays You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. The following code line: document.write(mycars[0]) will result in the following output: Saab

Modify Values in Existing Arrays To modify a value in an existing array, just add a new value to the array with a specified index number: mycars[0]="Opel" Now, the following code line: document.write(mycars[0])

will result in the following output: Opel JavaScript Math Object The Math object allows you to perform common mathematical tasks. Math Object The Math object allows you to perform common mathematical tasks. The Math object includes several mathematical values and functions. You do not need to define the Math object before using it. Mathematical Values JavaScript provides eight mathematical values (constants) that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E. You may reference these values from your JavaScript like this: Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E

Mathematical Methods In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available. Examples of functions (methods): The following example uses the round() method of the Math object to round a number to the nearest integer: document.write(Math.round(4.7)) The code above will result in the following output: 5

The following example uses the random() method of the Math object to return a random number between 0 and 1: document.write(Math.random()) The code above can result in the following output: 0.8669997601016495 The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10: document.write(Math.floor(Math.random()*11)) The code above can result in the following output: 3

The Navigator Object The JavaScript Navigator object contains all information about the visitor's browser. We are going to look at two properties of the Navigator object: appName - holds the name of the browser appVersion - holds, among other things, the version of the browser Example <html> <body> <script> with(navigator) { document.writeln("Browser Code Name:"+appCodeName+"<br>") document.writeln("Browser Name:"+appName+"<br>") document.writeln("Browser Version:"+appVersion+"<br>") document.writeln("Language:"+language+"<br>") document.writeln("Operating Platform:"+platform+"<br>") document.writeln("User Agent:"+userAgent) } </script> </body> </html>

<html> <body> <script> with(navigator) { document.writeln("Browser Code Name:"+appCodeName+"<br>") document.writeln("Browser Name:"+appName+"<br>") document.writeln("Browser Version:"+appVersion+"<br>") document.writeln("Language:"+language+"<br>") document.writeln("Operating Platform:"+platform+"<br>") document.writeln("User Agent:"+userAgent) } </script> </body> </html> The variable browser in the example above holds the name of the browser, i.e. "Netscape" or "Microsoft Internet Explorer". The appVersion property in the example above returns a string that contains much more information than just the version number, but for now we are only interested in the version number. To pull the version number out of the string we are using a function called parseFloat(), which pulls the first thing that looks like a decimal number out of a string and returns it. IMPORTANT! The version number is WRONG in IE 5.0 or later! Microsoft start the appVersion string with the numbers 4.0. in IE 5.0 and IE 6.0!!! Why did they do that??? However, JavaScript is the same in IE6, IE5 and IE4, so for most scripts it is ok. Example The script below displays a different alert, depending on the visitor's browser: <html> <head> <script type="text/javascript"> function detectBrowser() { var browser=navigator.appName var b_version=navigator.appVersion var version=parseFloat(b_version) if ((browser=="Netscape"||browser=="Microsoft Internet Explorer") && (version>=4)) {alert("Your browser is good enough!")} else

{alert("It's time to upgrade your browser!")} } </script> </head> <body onload="detectBrowser()"> </body> </html>

JavaScript Timing Events With JavaScript, it is possible to execute some code NOT immediately after a function is called, but after a specified time interval. This is called timing events. JavaScript Timing Events With JavaScript, it is possible to execute some code NOT immediately after a function is called, but after a specified time interval. This is called timing events. It's very easy to time events in JavaScript. The two key methods that are used are: setTimeout() - executes a code some time in the future clearTimeout() - cancels the setTimeout() Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object. setTimeout() Syntax var t=setTimeout("javascript statement",milliseconds) The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name. The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()". The second parameter indicates how many milliseconds from now you want to execute the first parameter. Note: There are 1000 milliseconds in one second. clearTimeout()

Syntax clearTimeout(setTimeout_variable) Example When the button is clicked in the example below, an alert box will be displayed after 5 seconds. <html> <head> <script> var c=setTimeout("alert('Press the OK button to continue')",5000); function clr() { clearTimeout(c); alert("The setTimeout() method was cancelled"); } </script> </head> <body> <form> <input type="button" value="OK" onclick="clr()"> </form> </html> What is RegExp? A regular expression is an object that describes a pattern of characters. When you search in a text, you can use a pattern to describe what you are searching for. A simple pattern can be one single character. A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more. Regular expressions are used to perform powerful pattern-matching and "search-andreplace" functions on text. Syntax var patt=new RegExp(pattern,modifiers); or more simply: var patt=/pattern/modifiers;

pattern specifies the pattern of an expression modifiers specify if a search should be global, case-insensitive, etc. RegExp Modifiers Modifiers are used to perform case-insensitive and global searches. The i modifier is used to perform case-insensitive matching. The g modifier is used to perform a global match (find all matches rather than stopping after the first match). Modifiers Modifiers are used to perform case-insensitive and global searches: Modifier i g m Brackets Brackets are used to find a range of characters: Expression [abc] [^abc] [0-9] [A-Z] [a-z] [A-z] [adgk] [^adgk] (red|blue|green) Metacharacters Description Find any character between the brackets Find any character not between the brackets Find any digit from 0 to 9 Find any character from uppercase A to uppercase Z Find any character from lowercase a to lowercase z Find any character from uppercase A to lowercase z Find any character in the given set Find any character outside the given set Find any of the alternatives specified Description Perform case-insensitive matching Perform a global match (find all matches rather than stopping after the first match) Perform multiline matching

Metacharacters are characters with a special meaning: Metacharacter . \w \W \d \D \s \S \b \B \0 \n \f \t Working Example: Description Find a single character, except newline or line terminator Find a word character Find a non-word character Find a digit Find a non-digit character Find a whitespace character Find a non-whitespace character Find a match at the beginning/end of a word Find a match not at the beginning/end of a word Find a NUL character Find a new line character Find a form feed character Find a tab character

<script type='text/javascript'> function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; }

} </script> <form> Numbers Only: <input type='text' id='numbers'/> <input type='button' onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')" value='Check Field' /> </form> We wanted to see if the input's string was all numbers so we made a regular expression to check for numbers [0-9] and stored it as numericExpression. We then used the match function with our regular expression. If it is numeric then match will return true, making our if statement pass the test and our function isNumeric will also return true. However, if the expression fails because there is a letter or other character in our input's string then we'll display our helperMsg and return false.

Wor king Example:

<script type='text/javascript'> function lengthRestriction(elem, min, max){ var uInput = elem.value;

if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } </script> <form> Username(6-8 characters): <input type='text' id='restrict'/> <input type='button' onclick="lengthRestriction(document.getElementById('res trict'), 6, 8)" value='Check Field' /> </form> Above we have created a lengthRestriction function that takes a text field and two numbers. The first number is the minimum number of characters and the second is the maximum number of a characters the input can be. If you just want to specify an exact number then send the same number for both minimum and maximum.

Email validation Example The regular expression to check for all of this is a little overkill and beyond the scope of this tutorial to explain thoroughly. However, test it out and you'll see that it gets the job done.

Wor king Example:

<script type='text/javascript'> function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zAz0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } </script> <form> Email: <input type='text' id='emailer'/>

<input type='button' onclick="emailValidator1(document.getElementById('email er'), 'Not a Valid Email')" value='Check Field' /> </form>

Validations in J avascr ipt

<script type='text/javascript'>

function formValidator(){ // Make quick references to our fields var firstname = document.getElementById('firstname'); var addr = document.getElementById('addr'); var zip = document.getElementById('zip'); var state = document.getElementById('state'); var username = document.getElementById('username'); var email = document.getElementById('email');

// Check each input in the order that it appears in the form! if(isAlphabet(firstname, "Please enter only letters

for your name")){ if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){ if(isNumeric(zip, "Please enter a valid zip code")){ if(madeSelection(state, "Please Choose a State")){ if(lengthRestriction(username, 6, 8)){ if(emailValidator(email, "Please enter a valid email address")){ return true; } } } } } }

return false;

function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); // set the focus to this input return false; } return true; }

function isNumeric(elem, helperMsg){

var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; }

function isAlphabet(elem, helperMsg){

var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }

function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }

function lengthRestriction(elem, min, max){ var uInput = elem.value;

if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false; } }

function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true;

function emailValidator(elem, helperMsg){

var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zAz0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } </script>

<form onsubmit='return formValidator()' > First Name: <input type='text' id='firstname' /><br /> Address: <input type='text' id='addr' /><br /> Zip Code: <input type='text' id='zip' /><br /> State: <select id='state'> <option>Please Choose</option> <option>AL</option> <option>CA</option> <option>TX</option> <option>WI</option> </select><br />

Username(6-8 characters): <input type='text' id='username' / ><br /> Email: <input type='text' id='email' /><br /> <input type='submit' value='Check Form' /> </form>

E-mail Validation another method

The function below checks if the content has the general syntax of an email. This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end

<html> <head> <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf(".");

if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; }} </script> </head>

<body> <form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="Submit"> </form> </body>

</html>

Changing Text with innerHTML Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more

interactive pages. However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers. After you have that set up you can now manipulate the text of an element. To start off, let's try changing the text inside a bold tag. JavaScript Code: <script type="text/javascript"> function changeText(){ document.getElementById('boldStuff').innerHTML = 'Fred Flinstone'; } </script> <p>Welcome to the site <b id='boldStuff'>dude</b> </p> <input type='button' onclick='changeText()' value='Change Text'/> Display: Welcome to the site dude Changing image in javascript <html> <head> <script type="text/javascript"> function image() {

document.getElementById('txt').src="123.gif"; //document.getElementById('txt').title="khalsa";

} function nn()

{ document.getElementById('txt').src="apple.jpg";

} </script> </head> <body>

<div id="text"> <img src="apple.jpg" id="txt" onmouseover="image()" onmouseout="nn()"/> </div> </body> </html> Changing Background Color o'clock <html> <head> <script type="text/javascript"> function bcol(bgc) { document.getElementById('e').style.backgroundColor=bgc; } </script> </head>

<body id="e"> <div style="background-color:red;height:20px;width:20px" onclick="bcol('red')"></div> <div style="background-color:green;height:20px;width:20px" onclick="bcol('green')"></div> <div style="background-color:black;height:20px;width:20px" onclick="bcol('black')"</div> </body> </html> SLIDER IN JAVASCRIPT <html> <head> <script type="text/javascript"> <!-var image1=new Image() image1.src="firstcar.gif" var image2=new Image() image2.src="secondcar.gif" var image3=new Image() image3.src="thirdcar.gif" //--> </script> </head> <body> <img src="firstcar.gif" name="slide" width="100" height="56" />

<script> <!-//variable that will increment through the images var step=1 function slideit(){ //if browser does not support the image object, exit. if (!document.images) return document.images.slide.src=eval("image"+step+".src") if (step<3) step++ else step=1 //call function "slideit()" every 2.5 seconds setTimeout("slideit()",2500) } slideit() //--> </script> </body> </html>

JavaScript Summary

This tutorial has taught you how to add JavaScript to your HTML pages, to make your web site more dynamic and interactive. You have learned how to create responses to events, validate forms and how to make different scripts run in response to different scenarios. You have also learned how to create and use objects, and how to use JavaScript's built-in objects.

PHP

PHP is a powerful server-side scripting language for creating dynamic and interactive websites.

PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded directly into the HTML code. The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows.

What is PHP?

PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software PHP is free to download and use

What is a PHP File?


PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

MySQL is a database server MySQL is ideal for both small and large applications MySQL supports standard SQL MySQL compiles on a number of platforms MySQL is free to download and use

PHP + MySQL

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Why PHP?

PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side

Download PHP Download PHP for free here: http://www.php.net/downloads.php Download MySQL Database Download MySQL for free here: http://www.mysql.com/downloads/index.html Download Apache Server Download Apache for free here: http://httpd.apache.org/download.cgi PHP code is executed on the server, and the plain HTML result is sent to the browser. Or Download Wamp,Xampp,Lamp Server WAMP-Windows software with Apache,Mysql and PHP XAMPP-Any Platform software with Apache,Mysql and PHP,PERL LAMP-Linux software with Apache,Mysql and PHP Basic PHP Syntax A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with

<? and end with ?>. For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form. <?php ?> A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser: <html> <body> <?php echo "Hello World"; ?> </body> </html> Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World". Note: The file must have the .php extension. If the file has a .html extension, the PHP code will not be executed. Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>

Variables in PHP Variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again in your script All variables in PHP start with a $ sign symbol. The correct way of setting a variable in PHP: $var_name = value; New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work. Let's try creating a variable with a string, and a variable with a number: <?php $txt = "Hello World!"; $number = 16; ?> PHP is a Loosely Typed Language In PHP a variable does not need to be declared before being set. In the example above, you see that you do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on how they are set. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP the variable is declared automatically when you use it. Variable Naming Rules

A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (az, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

PHP Operators This section lists the different operators used in PHP. Arithmetic Operators Operator Description Example + Addition x=2 x+2 Subtraction x=2 5-x * Multiplication x=4 x*5 / Division 15/5 5/2 % Modulus (division remainder) 5%2 10%8 10%2 ++ Increment x=5 x++ -Decrement x=5 x-Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y x=x.y %= x%=y x=x%y Comparison Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true Logical Operators Operator Description Example && and x=6 y=3

Result 4 3 20 3 2.5 1 2 0 x=6 x=4

||

or

(x < 10 && y > 1) returns true x=6 y=3 (x==5 || y==5) returns false x=6 y=3 !(x==y) returns true

not

The if, elseif and else statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true

The If...Else Statement If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement. Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else

echo "Have a nice day!"; ?> </body> </html> If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces: <html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html> The ElseIf Statement If you want to execute some code if one of several conditions are true use the elseif statement Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun")

echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html>

PHP Switch Statement The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions. The Switch Statement If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code. Syntax switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } Example This is how it works:

A single expression (most often a variable) is evaluated once The value of the expression is compared with the values for each

case in the structure If there is a match, the code associated with that case is executed After a code is executed, break is used to stop the code from running into the next case The default statement is used if none of the cases are true

<html> <body> <?php 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>

Looping statements in PHP are used to execute the same block of code a specified number of times. Looping Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements:

while - loops through a block of code if and as long as a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array

The while Statement The while statement will execute a block of code if and as long as a condition is true. Syntax while (condition) code to be executed; Example The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> The do...while Statement The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. Syntax do { code to be executed; } while (condition); Example The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5: <html> <body> <?php $i=0; do {

$i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html> The for Statement The for statement is the most advanced of the loops in PHP. In it's simplest form, the for statement is used when you know how many times you want to execute a statement or a list of statements. Syntax for (init; cond; incr) { code to be executed; } Parameters:

init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement. cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends. incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.

Note: Each of the parameters can be empty or have multiple expressions separated by commas.

cond: All expressions separated by a comma are evaluated but the result is taken from the last part. This parameter being empty means the loop should be run indefinitely. This is useful when using a conditional break statement inside the loop for ending the loop.

Example The following example prints the text "Hello World!" five times: <html> <body> <?php for ($i=1; $i<=5; $i++) {

echo "Hello World!<br />"; } ?> </body> </html> An array can store one or more values in a single variable name. What is an array? When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store the data as elements in an array. Each element in the array has its own ID so that it can be easily accessed. There are three different kind of arrays:

Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays

Numeric Arrays A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array. Example 1 In this example the ID key is automatically assigned: $names = array("Peter","Quagmire","Joe"); Example 2 In this example we assign the ID key manually: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; The ID keys can be used in a script: <?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?> The code above will output:

Quagmire and Joe are Peter's neighbors Associative Arrays An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them. 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. Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with automatically assigned ID keys: $products=array('Samsung'=>array( 'color'=>'red', 'price'=>20000) ,'lg'=>array( 'color'=>'black', 'price'=>30000) ); The array above would look like this if written to the output:

Array ( [Samsung] => Array ( [color] => red [price] => 20000 [2] => Megan ), [lg] => Array ( [color] => balck [price]=>30000 ) ) Output Lets try displaying a single value from the array above: echo "Price of Samsung is" . $products['Samsung']['Price'] ; The code above will output: Price of Samsung is 20000

The foreach Statement The foreach statement is used to loop through arrays. For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element. Syntax foreach (array as value) { code to be executed; } Example The following example demonstrates a loop that will print the values of the given array: <html> <body> <?php $arr=array(peter=>22,joe=>24,jack=>44);

foreach ($arr as $key=>$value) { echo Age of: .$key.is . $value . "<br />"; } ?> </body> </html>
Output Age of peter is 22 Age of joe is 24 Age of jack is 44

The real power of PHP comes from its functions. In PHP - there are more than 700 built-in functions available. PHP Functions In this tutorial we will show you how to create your own functions. Functions are of two types 1.Inbuilt functions 2.User Defined Functions Inbuilt String Functions Strings in PHP String variables are used for values that contains character strings. In this tutorial we are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string "Hello World" to a string variable called $txt: <?php $txt="Hello World"; echo $txt; ?> The output of the code above will be: Hello World

Now, lets try to use some different functions and operators to manipulate our string. The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two variables together, use the dot (.) operator: <?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2; ?> The output of the code above will be: Hello World 1234 If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string. Between the two string variables we added a string with a single character, an empty space, to separate the two variables. Using the strlen() function The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!": <?php echo strlen("Hello world!"); ?> The output of the code above will be: 12 The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string) PHP addcslashes() Function Definition and Usage The addcslashes() function returns a string with backslashes in front of the specified characters.

Syntax addcslashes(string,characters) Parameter string characters Example: $str="what a nice movie"; $res=addcslashes($str5,nve); echo $res; Output: Description Required. Specifies the string to check Required. Specifies the characters or range of characters to be affected by addcslashes()

what a \nic\e mo\vi\e


PHP addslashes() Function Definition and Usage The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: Syntax single quote (') double quote (") backslash (\) NULL

addslashes(string) Parameter string Example: $str5="what's going on"; $res5=addslashes($str5); echo $res5; Output: Description Required. Specifies the string to check

what\'s going on

PHP chr() Function Definition and Usage The chr() function returns a character from the specified ASCII value. Syntax chr(ascii) Parameter ascii Example: $res=chr(65); echo $res; Output A PHP nl2br() Function Definition and Usage The nl2br() function inserts HTML line breaks (<br />) in front of each newline (\n) in a string. Syntax nl2br(string) Parameter string Description Required. Specifies the string to check Description Required. An ASCII value

PHP strip_tags() Function Definition and Usage The strip_tags() function strips a string from HTML, XML, and PHP tags. Syntax strip_tags(string,allow)

Parameter string allow

Description Required. Specifies the string to check Optional. Specifies allowable tags. These tags will not be removed

PHP stripcslashes() Function Definition and Usage The stripcslashes() function removes backslashes added by the addcslashes() function. Syntax stripcslashes(string) Parameter string Description Required. Specifies the string to check

PHP stripslashes() Function Definition and Usage The stripslashes() function removes backslashes added by the addslashes() function. Syntax stripslashes(string) Parameter string PHP htmlentities() Function Definition and Usage The htmlentities() function converts characters to HTML entities. Syntax htmlentities(string,quotestyle,character-set) Description Required. Specifies the string to check

Parameter string quotestyle

Description Required. Specifies the string to convert Optional. Specifies how to encode single and double quotes. The available quote styles are: ENT_COMPAT Default. Encodes only double quotes ENT_QUOTES Encodes double and single quotes ENT_NOQUOTES Does not encode any quotes Optional. A string that specifies which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1) UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windowsspecific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions

character-set

Example : echo htmlentities("<h1>hello</h1>"); Output: <h1>hello</h1> PHP htmlspecialchars() Function

Shift_JIS - Japanese EUC-JP - Japanese

Definition and Usage The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are: Syntax & (ampersand) becomes &amp; " (double quote) becomes &quot; ' (single quote) becomes &#039; < (less than) becomes &lt; > (greater than) becomes &gt;

htmlspecialchars(string,quotestyle,character-set) Parameter string quotestyle Description Required. Specifies the string to convert Optional. Specifies how to encode single and double quotes. The available quote styles are: ENT_COMPAT Default. Encodes only double quotes ENT_QUOTES Encodes double and single quotes ENT_NOQUOTES Does not encode any quotes Optional. A string that specifies

character-set

which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1) UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windowsspecific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions Shift_JIS - Japanese EUC-JP - Japanese PHP html_entity_decode() Function

Definition and Usage The html_entity_decode() function converts HTML entities to characters. The html_entity_decode() function is the opposite of htmlentities(). Syntax html_entity_decode(string,quotestyle,character-set) Parameter Description

string quotestyle

Required. Specifies the string to decode Optional. Specifies how to decode single and double quotes. The available quote styles are: ENT_COMPAT Default. Decodes only double quotes ENT_QUOTES Decodes double and single quotes ENT_NOQUOTES Does not decode any quotes Optional. A string that specifies which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1) UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windowsspecific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions Shift_JIS - Japanese EUC-JP - Japanese

character-set

PHP htmlspecialchars() Function

Definition and Usage The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are: Syntax & (ampersand) becomes &amp; " (double quote) becomes &quot; ' (single quote) becomes &#039; < (less than) becomes &lt; > (greater than) becomes &gt;

htmlspecialchars(string,quotestyle,character-set) Parameter string quotestyle Description Required. Specifies the string to convert Optional. Specifies how to encode single and double quotes. The available quote styles are: ENT_COMPAT Default. Encodes only double quotes ENT_QUOTES Encodes double and single quotes ENT_NOQUOTES Does not encode any quotes Optional. A string that specifies which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-8859-1)

character-set

UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windowsspecific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions Shift_JIS - Japanese EUC-JP - Japanese

PHP md5() Function Definition and Usage The md5() function calculates the MD5 hash of a string. The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." This function returns the calculated MD5 hash on success, or FALSE on failure. Syntax

md5(string,raw) Parameter string raw Description Required. The string to be calculated Optional. Specifies hex or binary output format: TRUE - Raw 16 character binary format FALSE - Default. 32 character hex number Note: This parameter was added in PHP 5.0

Example $str="Powerx123"; $res=md5($str); echo $res; Output 850225b028a7f49d00d47e662ab65220 PHP sha1() Function Definition and Usage The sha1() function calculates the SHA-1 hash of a string. The sha1() function uses the US Secure Hash Algorithm 1. From RFC 3174 - The US Secure Hash Algorithm 1: "SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature." This function returns the calculated SHA-1 hash on success, or FALSE on failure. Syntax sha1(string,raw) Parameter string Description Required. The string to be calculated

raw

Optional. Specify hex or binary output format: TRUE - Raw 20 character binary format FALSE - Default. 40 character hex number Note: This parameter was added in PHP 5.0

Example: $res1=sha1($str); echo $res1; Output 0360d45f013fabbe3fa538c35feec4cd5f59484a PHP explode() Function Definition and Usage The explode() function breaks a string into an array. Syntax explode(separator,string,limit) Parameter separator string limit Example: $str="happy new year 2013"; $a=explode(" ",$str,2); print_r($a); Output Array ( [0] => happy [1] => new year 2013 ) PHP implode() Function The implode() function returns a string from the elements of an array. Description Required. Specifies where to break the string Required. The string to split Optional. Specifies the maximum number of array elements to return

Syntax implode(separator,array) Parameter separator array Example: $b=array("hello","user","how","are","u"); $str2=implode(" ",$b); echo $str2; Output: hello user how are u PHP str_replace()Function Definition and Usage The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array If the string to be searched is an array, find and replace is performed with every array element If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace If find is an array and replace is a string, the replace string will be used for every find value Syntax str_replace(find,replace,string,count) Parameter find replace Description Required. Specifies the value to find Required. Specifies the value to Description Optional. Specifies what to put between the array elements. Default is "" (an empty string) Required. The array to join to a string

string count

replace the value in find Required. Specifies the string to be searched Optional. A variable that counts the number of replacements

Tips and Notes Note: This function is case-sensitive. Use str_ireplace() to perform a case-insensitive search. Note: This function is binary-safe. Example 1 <?php echo str_replace("world","Peter","Hello world!"); ?> The output of the code above will be: Hello Peter!

Example 2 In this example we will demonstrate str_replace() with an array and a count variable: <?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; ?> The output of the code above will be: Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1

Example 3 In this example we will demonstrate str_replace() with less elements in replace than find: <?php $find = array("Hello","world"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_replace($find,$replace,$arr)); ?> The output of the code above will be: Array ( [0] => B [1] => [2] => ! ) PHP strcmp() Function Definition and Usage The strcmp() function compares two strings. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2 Syntax strcmp(string1,string2) Parameter string1 string2 Description Required. Specifies the first string to compare Required. Specifies the second string to compare

Tips and Notes Note: The strcmp() function is binary safe and case-sensitive. Example

<?php echo strcmp("Hello world!","Hello world!"); ?> The output of the code above will be: 0 PHP strpos() Function Definition and Usage The strpos() function returns the position of the first occurrence of a string inside another string. If the string is not found, this function returns FALSE. Syntax strpos(string,find,start) Parameter string find start Description Required. Specifies the string to search Required. Specifies the string to find Optional. Specifies where to begin the search

Tips and Notes Note: The strpos() function is case-sensitive. Example <?php echo strpos("Hello world!","wo"); ?> The output of the code above will be: 6 PHP strrev() Function Definition and Usage The strrev() function reverses a string.

Syntax strrev(string) Parameter string Description Required. Specifies the string to reverse

Example <?php echo strrev("Hello World!"); ?> The output of the code above will be: !dlroW olleH PHP substr() Function Definition and Usage The substr() function returns a part of a string. Syntax substr(string,start,length) Parameter string start Description Required. Specifies the string to return a part of Required. Specifies where to start in the string A positive number - Start at a specified position in the string A negative number - Start at a specified position from the end of the string 0 - Start at the first character in string Optional. Specifies the length of the returned string. Default is to the end of the string. A positive number - The length to be returned from the start

length

parameter Negative number - The length to be returned from the end of the string

Tips and Notes Note: If start is a negative number and length is less than or equal to start, length becomes 0. Example 1 <?php echo substr("Hello world!",6); ?> The output of the code above will be: world!

Example 2 <?php echo substr("Hello world!",6,5); ?> The output of the code above will be: world PHP chunk_split() Function chunk_split(string,length,end) Parameter string length end PHP date() Function Description Required. Specifies the string to split Optional. A number that defines the length of the chunks. Default is 76 Optional. A string that defines what to place at the end of each chunk. Default is \r\n

Definition and Usage The date() function formats a local time/date. Syntax date(format,timestamp)
Parameter format Description Required. Specifies how to return the result: d - The day of the month (from 01 to 31) D - A textual representation of a day (three letters) j - The day of the month without leading zeros (1 to 31) l (lowercase 'L') - A full textual representation of a day N - The ISO-8601 numeric representation of a day (1 for Monday through 7 for Sunday) S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j) w - A numeric representation of the day (0 for Sunday through 6 for Saturday) z - The day of the year (from 0 through 365) W - The ISO-8601 week number of year (weeks starting on Monday) F - A full textual representation of a month (January through December) m - A numeric representation of a month (from 01 to 12) M - A short textual representation of a month (three letters) n - A numeric representation of a month, without leading zeros (1 to 12) t - The number of days in the given month

L - Whether it's a leap year (1 if it is a leap year, 0 otherwise) o - The ISO-8601 year number Y - A four digit representation of a year y - A two digit representation of a year a - Lowercase am or pm A - Uppercase AM or PM B - Swatch Internet time (000 to 999) g - 12-hour format of an hour (1 to 12) G - 24-hour format of an hour (0 to 23) h - 12-hour format of an hour (01 to 12) H - 24-hour format of an hour (00 to 23) i - Minutes with leading zeros (00 to 59) s - Seconds, with leading zeros (00 to 59) e - The timezone identifier (Examples: UTC, Atlantic/Azores) I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise) O - Difference to Greenwich time (GMT) in hours (Example: +0100) T - Timezone setting of the PHP machine (Examples: EST, MDT) Z - Timezone offset in seconds. The offset west of UTC is negative, and the offset east of UTC is positive (43200 to 43200) c - The ISO-8601 date (e.g. 2004-0212T15:19:21+00:00) r - The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07 +0200) U - The seconds since the Unix Epoch (January 1 1970

timestamp

00:00:00 GMT) Optional.

User Defined Functions php Create a PHP Function A function is a block of code that can be executed whenever we need it. Creating PHP functions:

All functions start with the word "function()" Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) Add a "{" - The function code starts after the opening curly brace Insert the function code Add a "}" - The function is finished by a closing curly brace

Example A simple function that writes my name when it is called: <html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } writeMyName(); ?> </body> </html> Use a PHP Function Now we will use the function in a PHP script: <html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes";

} echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?> </body> </html> The output of the code above will be: Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my name. PHP Functions - Adding parameters Our first function (writeMyName()) is a very simple function. It only writes a static string. To add more functionality to a function, we can add parameters. A parameter is just like a variable. You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses. Example 1 The following example will write different first names, but the same last name: <html> <body> <?php function writeMyName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeMyName("Kai Jim"); echo "My name is "; writeMyName("Hege"); echo "My name is "; writeMyName("Stale"); ?> </body> </html> The output of the code above will be: My name is Kai Jim Refsnes.

My name is Hege Refsnes. My name is Stale Refsnes. Example 2 The following function has two parameters: <html> <body> <?php function writeMyName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeMyName("Kai Jim","."); echo "My name is "; writeMyName("Hege","!"); echo "My name is "; writeMyName("Stle","..."); ?> </body> </html> The output of the code above will be: My name is Kai Jim Refsnes. My name is Hege Refsnes! My name is Stle Refsnes... PHP Functions - Return values Functions can also be used to return values. Example <html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> The output of the code above will be:

1 + 16 = 17

The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Form example: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file. The "welcome.php" file looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> A sample output of the above script may be: Welcome John. You are 28 years old. The PHP $_GET and $_POST variables will be explained in the next chapters. Form Validation User input should be validated whenever possible. Client side validation is faster, and will reduce server load. However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database.

A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error. The $_GET variable is used to collect values from a form with method="get". The $_GET Variable The $_GET variable is an array of variable names and values sent by the HTTP GET method. The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters). Example <form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL sent could look something like this: http://www.w3schools.com/welcome.php?name=Peter&age=37 The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array): Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! Why use $_GET? Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters. The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!

The $_POST variable is used to collect values from a form with method="post". The $_POST Variable The $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Example <form action="welcome.php" method="post"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array): Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! Why use $_POST?

Variables sent with HTTP POST are not shown in the URL Variables have no length limit

However, because the variables are not displayed in the URL, it is not possible to bookmark the page. The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!

The PHP date() function is used to format a time or a date. The PHP Date() Function The PHP date() function formats a timestamp to a more readable date and time. Syntax date(format,timestamp) Parameter format timestamp Description Required. Specifies the format of the timestamp Optional. Specifies a timestamp. Default is the current date and time (as a timestamp)

PHP Date - What is a Timestamp? A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp. PHP Date - Format the Date The first parameter in the date() function specifies how to format the date/time. It uses letters to represent date and time formats. Here are some of the letters that can be used:

d - The day of the month (01-31) m - The current month, as a number (01-12) Y - The current year in four digits

Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting: <?php echo date("Y/m/d"); echo "<br />"; echo date("Y.m.d"); echo "<br />"; echo date("Y-m-d"); ?> The output of the code above could be something like this: 2006/07/11

2006.07.11 2006-07-11 PHP Date - Adding a Timestamp Displaying Date and Time The date and time we will show how to display in this tutorial is the one specified by the server which is hosting our pages. In case you want to display a different date or time (p. e., your clients are mostly from Belgium but your server is located in US and you want to display the local time in Belgium) you will find how to do it latter on this page. In the table bellow we have include the PHP code necessary to display one by one all the time and date related information. By copying the code in the first column to your page you will get the data which is explained in the third column. The column in the middle is the value of those data the day we were preparing this page. Code Output <?php print pm date("a"); ?> <?php print PM date("A"); ?> <?php print 15 date("d"); ?> <?php print Tue date("D"); ?> <?php print October date("F"); ?> <?php print 03 date("h"); ?> <?php print 15 date("H"); ?> <?php print 3 date("g"); ?> <?php print 15 date("G"); ?> <?php print date("i"); ? 26 > <?php print date("j"); ? 15 > <?php print date("l"); ? Tuesday >

"am" or "pm" "AM" or "PM" Day of the month: 01 to 31 Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat Month: January, February, March... Hour: 01 to 12 Hour: 00 to 23 Hour: 1 to 12 Hour: 0 to 23 Minutes: 00 to 59 Day of the month: 1 to 31 Day of the week: Sunday, Monday, Tuesday...

<?php print 0 date("L"); ?> <?php print date("m"); 10 ?> <?php print 10 date("n"); ?> <?php print date("M"); Oct ?> <?php print date("s"); ? 03 > <?php print date("S"); ?> th

Is it a leap year? 1 (yes) or 0 (no) Month: 01 to 12 Month: 1 to 12 Month: Jan, Feb, Mar, Apr, May... Seconds: 00 to 59 Ordinal: 1st, 2st, 3st, 4st... Need to be used with a numeric time/date value. See latter. Number of days in the month: 28 to 31 Seconds since 1970/01/01 00:00:00 Day of the week: 0 (Sunday) to 6 (Saturday) Year (four digits) Year (two digits) Day of the year: 0 to 365 Difference in seconds from Greenwhich meridian

<?php print date("t"); ? 31 > <?php print 103469196 date("U"); ?> 3 <?php print 2 date("w"); ?> <?php print 2002 date("Y"); ?> <?php print 02 date("y"); ?> <?php print 287 date("z"); ?> <?php print -21600 date("Z"); ?>

As shown in the table the commands we are using in all case are "print" (in order to show the values to the visitor) and "date" (which will allow us to get the data corresponding to the string code we are using between brakets). So we already know how to obtain the data and how to show it in our page, but if we want to display different values simultaneously, we have at least three option: The code <?php print date("Y"); ?>:<?php print date("m"); ?>:<?php print date("d"); ?> <?php print date("Y").":".date("m").":".date("d"); ?> <?php print date("Y:m:d"); ?> Output 2002:10:1 5 2002:10:1 5 2002:10:1

5 The first option is very easy to understand (we have just copied the code from the table one by one). The second option concatenates the data basically in the same way, and the third one is probably the most useful system, but the one we must understand before using it. Command "date" will get the data we want to display, and that data is specified by the string used within data (in our case: "Y:m:d"). Each character in this string may or may not have a meaning depending upon there is or there is not a value asociate with that letter (see the first table in this page). In our case some characters will be replaced by its corresponding value: Y : m : d Check this usefull examples: The code <?php print date("Y:m:d H:i") ?> <?php print date("l dS of F Y h:i:s A"); ?> The time is <?php print date("H:i") ?>. That means it's <?php print date("i") ?> minutes past <?php print date("H") ?> o'clock. Output 2002:10:15 15:26 Tuesday 15th of October 2002 15:26:03 PM The time is 15:26. That means it's 26 minutes past 15 o'clock. Year (four digits) no meaning Month: 01 to 12 no meaning Day of the month: 01 to 31

Take care when using date command or you may get unwanted data as shown in the first row in the table bellow (use the code in second row instead): The code <?php print date("Today is l"); ?> <?php print "Today is ".date("l"); ?> Output Character with meaning WETo15pm02 2603 The following characters have a Tuesday meaning: T, d, a, y, i, s, l Today is Tuesday Only data asociated to "l" (day of the week) is requested

Example: Link of the Day What if you wanted to have a link that points to a different page every day of the week? Here's how you can do that. First, create one page for each day of the week and name them "Sunday.htm," "Monday.htm," and so on. To make the link, copy the code bellow to your page <a href= <?php print date("l"); ?>.htm>Link of the Day</a> Place the code in your ".php" page where you want it to appear. When you click this link in your browser, it will take you to the "Link of the Day". Using "S" with date comand. Lets suppose we are using the code bellow in different consecutive days: Day Code Output 2002/01/0 <? php print date("nS of 1st of January 1 F"); ?> 2002/01/0 <? php print date("nS of 2nd of 2 F"); ?> January 2002/01/0 <? php print date("nS of 3rd of 3 F"); ?> January 2002/01/0 <? php print date("nS of 4th of 4 F"); ?> January The "S" character included within command date will allow us to show "st", "nd", "rd" or "th" values depending on the number preceding the character "S". Displaying local time In this tutorial we will consider our server is located in a different time zone from the one our clients are located at (a Belgium related site is in a server located is USA for example). First we must know the time in the server. We will create a text file with the code bellow, and we will copy it to our server: Time in server: <?php print date("H:i") ?> Then we will visit our page and we will get the time in the server. Let suppose the time is 16:00 Second, we will calculate the difference in hours between local time and the time in server. Let suppose the time in Belgium is 20:00, so the difference is 4 hours.

To get the local time we will use the code in the table bellow: <?php $differencetolocaltime=4; $new_U=date("U")$differencetolocaltime*3600; print date("H:i", $new_U); ?> Lets explain this code:

We have create a variable named $differencetolocaltime, and we have stablish the value for this variable (4) In third line of the script we have create a variable named $new_U, and the value for this variable will be 'date("U")' (Seconds since 1970/01/01 00:00:00) to which we have substracted the difference of hours between the two time zones (in our case 4 hours, which is the value for the variable $differencetolocaltime, has been multiplied by 3600, which is the number of seconds in one hour) In the last step we have write to the document the new hour and time by using "date" command to which we have let know the exact date (specified by $new_U) from which we want to get the time (if it is not specified, as for example when using 'date("H:i")', the time and date in the server will be displayed as shown before in this page).

The second parameter in the date() function specifies a timestamp. This parameter is optional. If you do not supply a timestamp, the current time will be used. In our next example we will use the mktime() function to create a timestamp for tomorrow. The mktime() function returns the Unix timestamp for a specified date. Syntax mktime(hour,minute,second,month,day,year,is_dst) To go one day in the future we simply add one to the day argument of mktime(): <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> The output of the code above could be something like this: Tomorrow is 2006/07/12

Server Side Includes (SSI) are used to create functions, headers, footers, or elements

that will be reused on multiple pages. Server Side Includes You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages). The include() Function The include() function takes all the text in a specified file and copies it into the file that uses the include function. Example 1 Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this: <html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> Example 2 Now, let's assume we have a standard menu file that should be used on all pages (include files usually have a ".php" extension). Look at the "menu.php" file below: <html> <body> <a href="http://www.w3schools.com/default.php">Home</a> | <a href="http://www.w3schools.com/about.php">About Us</a> | <a href="http://www.w3schools.com/contact.php">Contact Us</a> The three files, "default.php", "about.php", and "contact.php" should all include the "menu.php" file. Here is the code in "default.php": <?php include("menu.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body>

</html> If you look at the source code of the "default.php" in a browser, it will look something like this: <html> <body> <a href="default.php">Home</a> | <a href="about.php">About Us</a> | <a href="contact.php">Contact Us</a> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> And, of course, we would have to do the same thing for "about.php" and "contact.php". By using include files, you simply have to update the text in the "menu.php" file if you decide to rename or change the order of the links or add another web page to the site. The require() Function The require() function is identical to include(), except that it handles errors differently. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). If you include a file with the include() function and an error occurs, you might get an error message like the one below. PHP code: <html> <body> <?php include("wrongFile.php"); echo "Hello World!"; ?> </body> </html> Error message: Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5

Hello World! Notice that the echo statement is still executed! This is because a Warning does not stop the script execution. Now, let's run the same example with the require() function. PHP code: <html> <body> <?php require("wrongFile.php"); echo "Hello World!"; ?> </body> </html> Error message: Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 The echo statement was not executed because the script execution stopped after the fatal error. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed. The fopen() function is used to open files in PHP. Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> The file may be opened in one of the following modes: Modes Description

r r+ w

Read only. Starts at the beginning of the file Read/Write. Starts at the beginning of the file Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist Read/Append. Preserves file content by writing to the end of a+ the file x Write only. Creates a new file. Returns FALSE and an error if file already exists x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html> Closing a File The fclose() function is used to close an open file: <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?> Check End-of-file The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file"; Reading a File Line by Line

The fgets() function is used to read a single line from a file. Note: After a call to this function the file pointer has moved to the next line. Example The example below reads a file line by line, until the end of file is reached: <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?> Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. Example The example below reads a file character by character, until the end of file is reached: <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>

With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br />

<input type="submit" name="submit" value="Submit" /> </form> </body> </html> Notice the following about the HTML form above:

The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads. Create The Upload Script The "upload_file.php" file contains the code for uploading a file: <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } ?> By using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:

$_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Restrictions on Upload In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } ?> Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg. Saving the Uploaded File The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server. The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else

{ echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> The script above checks if the file already exists, if it does not, it copies the file to the specified folder. cookie is often used to identify a user. What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie(name, value, expire, path, domain); Example 1 In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour: <?php setcookie("user", "Alex Porter", time()+3600);

?> <html> ..... Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead). Example 2 You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html> ..... In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days). How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?> In the following example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html> How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> What if a Browser Does NOT Support Cookies? If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial). The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> Retrieve the values in the "welcome.php" file like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>

The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. PHP Error Handling When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. This tutorial contains some of the most common error checking methods in PHP. We will show different error handling methods:

Simple "die()" statements

Custom errors and error triggers Error reporting

Basic Error Handling: Using the die() function The first example shows a simple script that opens a text file: <?php $file=fopen("welcome.txt","r"); ?> If the file does not exist you might get an error like this: Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2 To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it: <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> Now if the file does not exist you get an error like this: File not found The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error. However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors. PHP AND MYSQL The free MySQL database is very often used with PHP. Create a Connection to a MySQL Database Before you can access data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function. Syntax mysql_connect(servername,username,password); Parameter Description

servername username password

Optional. Specifies the server to connect to. Default value is "localhost:3306" Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process Optional. Specifies the password to log in with. Default is ""

Example In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails: <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?> Closing a Connection The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?>

database holds one or multiple tables.

Insert Data Into a Database Table The INSERT INTO statement is used to add new records to a database table.

Syntax It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...) The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

Example In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); mysql_close($con); ?> Insert Data From a Form Into a Database Now we will create an HTML form that can be used to add new records to the "Persons" table. Here is the HTML form: <html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body>

</html> When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php". The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the "Persons" table. Here is the "insert.php" page: <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?>

The SELECT statement is used to select data from a database. Select Data From a Database Table The SELECT statement is used to select data from a database. Syntax SELECT column_name(s) FROM table_name To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all the data stored in the "Persons" table (The * character selects all the data in the table): <?php

$con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } mysql_close($con); ?> The example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']). The output of the code above will be: Peter Griffin Glenn Quagmire Display the Result in an HTML Table The following example selects the same data as the example above, but will display the data in an HTML table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons"); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>";

while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> The output of the code above will be: Firstna Lastnam me e Quagmir Glenn e Peter Griffin The WHERE clause is used to filter records. The WHERE clause The WHERE clause is used to extract only those records that fulfill a specified criterion. Syntax SELECT column_name(s) FROM table_name WHERE column_name operator value To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all rows from the "Persons" table where "FirstName='Peter': <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?> The output of the code above will be: Peter Griffin The WHERE clause is used to filter records. The WHERE clause The WHERE clause is used to extract only those records that fulfill a specified criterion. Syntax SELECT column_name(s) FROM table_name WHERE column_name operator value To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all rows from the "Persons" table where "FirstName='Peter': <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) {

echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?> The output of the code above will be: Peter Griffin

The ORDER BY keyword is used to sort the data in a recordset. The UPDATE statement is used to modify data in a table. Update Data In a Database The UPDATE statement is used to update existing records in a table. Syntax UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example Earlier in the tutorial we created a table named "Persons". Here is how it looks: FirstName LastName Age Peter Griffin 35 Glenn Quagmire 33 The following example updates some data in the "Persons" table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con);

mysql_query("UPDATE Persons SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); mysql_close($con); ?> After the update, the "Persons" table will look like this: FirstName LastName Peter Griffin Glenn Quagmire The DELETE statement is used to delete records in a table.

Age 36 33

Delete Data In a Database The DELETE FROM statement is used to delete records from a database table. Syntax DELETE FROM table_name WHERE some_column = some_value Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example Look at the following "Persons" table: FirstName LastName Age Peter Griffin 35 Glenn Quagmire 33 The following example deletes all the records in the "Persons" table where LastName='Griffin': <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); mysql_close($con); ?>

After the deletion, the table will look like this: FirstName LastName Glenn Quagmire

Age 33

ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an MS Access database). Create an ODBC Connection With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available. Here is how to create an ODBC connection to a MS Access Database:
1. 2. 3. 4. 5. 6. 7. 8.

Open the Administrative Tools icon in your Control Panel. Double-click on the Data Sources (ODBC) icon inside. Choose the System DSN tab. Click on Add in the System DSN tab. Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Give the database a Data Source Name (DSN). Click OK.

Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use. Connecting to an ODBC The odbc_connect() function is used to connect to an ODBC data source. The function takes four parameters: the data source name, username, password, and an optional cursor type. The odbc_exec() function is used to execute an SQL statement. Example The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it: $conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); Retrieving Records The odbc_fetch_row() function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false. The function takes two parameters: the ODBC result identifier and an optional row

number: odbc_fetch_row($rs) Retrieving Fields from a Record The odbc_result() function is used to read fields from a record. This function takes two parameters: the ODBC result identifier and a field number or name. The code line below returns the value of the first field from the record: $compname=odbc_result($rs,1); The code line below returns the value of a field called "CompanyName": $compname=odbc_result($rs,"CompanyName"); Closing an ODBC Connection The odbc_close() function is used to close an ODBC connection. odbc_close($conn); An ODBC Example The following example shows how to first create a database connection, then a resultset, and then display the data in an HTML table. <html> <body> <?php $conn=odbc_connect('northwind','',''); if (!$conn) {exit("Connection Failed: " . $conn);} $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); if (!$rs) {exit("Error in SQL");} echo "<table><tr>"; echo "<th>Companyname</th>"; echo "<th>Contactname</th></tr>"; while (odbc_fetch_row($rs)) { $compname=odbc_result($rs,"CompanyName"); $conname=odbc_result($rs,"ContactName"); echo "<tr><td>$compname</td>"; echo "<td>$conname</td></tr>"; } odbc_close($conn); echo "</table>"; ?> </body> </html>

Você também pode gostar