Professional Documents
Culture Documents
What is HTML?
• HTML(Hyper Text Markup Language)
is a language for describing web pages.
not a programming language
uses markup tags to describe web pages.
• Most Web documents are created using HTML.
Documents are saved with extension .html or .htm.
• Markup?
Markup Tags are strings in the language surrounded by a < and a > sign.
Opening tag: <html> Ending tag: </html>
Not case sensitive.
Can have attributes which provide additional information about HTML
elements on your page. Example
o <body bgcolor="red">
o <table border="0">
3
HTML
• An HTML document appears as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
HTML Head Section: contain information about the document. The browser does
not display this information to the user. Following tags can be in the head section:
<base>, <link>, <meta>, <script>, <style>, and <title>.
HTML Body Section: defines the document’s body. Contains all the contents of
the document (like text, images, colors, graphics, etc.).
4
<html>
<head><title>This is the first html page</title>
<body>This is the first html page created
<h1 align=”left”>This is level 1 heading</h1>
<h2 align=”right”>This is level 2 heading</h2>
<h3 align=”center”>This is level 3 heading</h3>
</body>
</head>
</html>
6
• Select the type of numbering system with the type attribute. Example:
o A-Uppercase letters. <OL TYPE=A>
o a-Lowercase letters. <OL TYPE=a>
o I-Uppercase Roman letters
o i-Lowercase Roman letters
o 1-Standard numbers, default
7
• To change the type of bullet used throughout the list, place the TYPE
attribute in the <UL> tag at the beginning of the list.
DISC (default) gives bullet in disc form.
SQUARE gives bullet in square form.
CIRCLE gives bullet in circle form.
<ul>
<li type=‘disc’>Latte</li>
<li type=‘square’>Expresso</li>
<li type=‘circle’>Mocha</li>
</ul>
8
Adding Image
• Images are added into a document using <img> tag.
• Attributes of <img> tag are:
alt: Alternative text to display for non-graphical browsers.
align: Image horizontal alignment. Valid values: left, right, center.
width/Height: Sets the width and height of the image.
src: Specifies the image path or source.
9
Table
• Use <table> tag to create a table.
• Table Attributes:
Border: <table border=“2”>………</table>
Align: defines the horizontal alignment of the table element.
o Values of the align attribute are right, left and center. <table align=“center”>
Width: defines the width of the table element.
o <table width=“75%”>………</table>
o <table width=“400”>………</table>
• Example:
<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
10
Table Data
• An HTML table has two kinds of cells:
Header Cells <th>: Contain header information (created with <th> element) ;
The text is bold and centered.
Standard Cells <td>: Contain data (created with the td element) ; The text is
regular and left-aligned.
<table>
<tr> <th>Column1 Header</th> <th>Column2 Header</th></tr>
<tr> <td>Cell 1,1</td> <td>Cell 1,2</td> </tr>
<tr> <td>Cell 2,1</td> <td>Cell 2,2</td> </tr>
</table>
• You can insert a bgcolor attribute in a <table>, <td>, <th> or <tr> tag to
set the color of the particular element.
<table bgcolor="cyan">
<tr bgcolor="blue">
11
Cell Spanning
• colspan="number of columns"
• rowspan="number of rows"
Forces a table cell to span the number of rows specified by the given value.
<table border=1>
<tr> <th>Column 1</th><th>Column 2</th><th>Column 3</th> </tr>
<tr>
<td rowspan=2>Column 1 Data</td>
<td align=center colspan=2>Col 2, Row 1 Data</td>
</tr>
<tr> <td>Col 2, Row 2 Data</td><td>Col 3, Row 2 Data</td>
</tr>
</table>
12
For documents located on other computers, attach the section name, preceded
by the # symbol, at the end of the document URL. Eg:
o I am working in <a ref=“http://www.state.edu/docs/add.htm#address1”>ABC</A>
To include a link to the named section from another local document :
o Please find relevant info in <A HREF=”report.htm#section1”>section 1</A>
13
Links to E-Mail
• “mailto” URL tag identifies the address to which an e-mail is to be sent
If the link is selected, the browser starts an email program to send a message
to the recipient listed in the URL.
Send me <A HREF=”mailto:abc@bcsbom.abc.com?subject=Mycomments”>
e-mail </A>with your comments about my page.<br>
<a href=“mailto:dude@abc.com?subject=More Info”>Contact Me</a><br>
Please <a href=“mailto:author@abc.com>mail</a> your comments to me.
Frame Basics
• Frames are created with <FRAMESET> and <FRAME> tags.
Don’t use <body></body> tags with <frameset> </frameset> tags.
• <Frameset> tag has two attributes: <frameset rows=“50%, 25%, 25%”>
<frameset rows=“150, *”>
rows and cols <frameset cols=“40%, *”>
• <Frame> : defines a frame within a frameset. Attributes :
src=“url”
name=“window_name” : optional
scrolling=“yes/no/auto” : “auto” displays a scrollbar when needed; is default
[noresize] <html>
<head> </head>
<frameset rows=10%,*>
<frame border=0 name=top src="top.html" noresize scrolling=no>
<frameset cols=20%,*>
<frame name=left src="Left.html">
<frameset rows=70%,*>
<frame name=main src="Main.html">
<frame name=details src="about:blank">
</frameset>
</frameset>
</frameset>
</html>
15
Text Field
• Single Line Text Fields: used to type letters, numbers, etc. in a form.
<INPUT TYPE=”type” NAME=”name” SIZE=”number” VALUE=”value” maxlength=n>
Eg: <form>
First name: <input type="text" name="firstname“ value=“fname>
Last name:<input type="text" name="lname">
</form>
Check Box
• Lets you select one or more options from a limited number of choices.
<input type=“checkbox” name=“name” value=“value” [checked]
[disabled]> Checkbox Label
Content of value attribute is sent to the form's action URL.
Radio Buttons
<input type=“radio” name=“name” value=“value” [checked] [disabled]>
Radio Button Label
• Content of the value attribute is sent to the form's action URL.
<form>
<input type="radio" name="sex" value="male"/>Male<br>
<input type="radio" name="sex" value="female"/> Female
</form>
18
Password Fields
• <input type=“password” name=“name” size=n value=“value” [disabled]>
Eg: Enter the password:<input type=“password” name=“passwd” size=20
value=“abc”>
Hidden Field
• Allows to pass information between forms:
• <input type=“hidden” name=“name” size=“n” value=“value”/>
• <input type=“hidden” name=“valid_user” size=“5” value=“yes”/>
Action Buttons
• To add a button to a form use:
<input type=“button” name=“btnCalculate” value=“Calculate”/>
• To submit the contents of the form use:
<input type=“submit” name=“btnSubmit” value=“Submit”/>
• To reset the field contents use:
<input type=“reset” name=“btnReset” value=“Reset”/>
• You can also create button using <button> tag ; defines a push
button. <button type="button">Click Me!</button>
Drop-Down List
<select name=“name” multiple=“true/false” size=n [disabled]>
<option [selected] [disabled] [value]>Option 1</option>…
</select>
Multiple: States if multiple element selection is allowed.
Size: Number of visible elements.
Disabled: States if the option is to be disabled after it first loads.
Introduction to HTML5 Enhanced Form Elements
• A Form is one of the most basic and essential feature of any web site
HTML5 brings 13 new input types
HTML5 introduces these data types via the <input
type=”_NEW_TYPE_HERE_”/> format
• In many cases, on a mobile device, changing the input type will also
cause the device to put up a custom keyboard to enable the user to
enter the right kind of data.
<audio controls>
<source src="vincent.mp3" type="audio/mpeg"/>
<source src="vincent.ogg" type="audio/ogg"/>
</audio>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
</script>
New Semantic Elements
• <section> : can be used to thematically group content
• <article>: represents a self-contained composition in a document, page,
application, or site that can be independently distributable or reusable
Eg a forum post, a magazine or newspaper article, a blog entry, a user comment
• <nav>: Represents a major navigation block. It groups links to other pages
or to parts of the current page.
• <Header>: tag specifies a header for a document or section. Can also be
used as a heading of an blog entry or news article as every article has its
title and published date and time
• <aside>: is a section that somehow related to main content, but it can be
separate from that content header and footer element in an article.
• <footer>: Similarly to "header" element, "footer" element is often referred
to the footer of a web page.
However, you can have a footer in every section, or every article too
• <figure>: The <figure> tag specifies self-contained content,
like illustrations, diagrams, photos, code listings, etc.
Using the Geolocation API
• geolocation is best described as the determination of the geographic
position of a person, place, or thing
Geolocation API is used to locate a user's position
• Test for the presence of the geolocation object:
if (navigator.geolocation) // check for Geolocation support
console.log('Geolocation is supported!');
else console.log('Geolocation is not supported for this Browser/OS version yet.');
function getLocation() {
var geolocation = navigator.geolocation;
geolocation.getCurrentPosition(showLocation, errorHandler);
}
Using the Geolocation API
• getCurrentPosition() method is called asynchronously with an object
Position which stores the complete location information.
The Position object specifies the current geographic location of the device
CSS Syntax
• A CSS rule has two parts: a selector, and one or more declarations:
Types of selectors
• HTML selectors
Used to define styles associated to HTML tags. – already seen!!!!
• Class selectors
Used to define styles that can be used without redefining plain HTML tags.
• ID selectors
Used to define styles relating to objects with a unique id
ID Selector <style>
H1.myClass {color: blue}
& Style .myOtherClass { color: red; text-align:center}
Sheet </style>
<body style="background: white; color:green">
Classes <H1 class="myClass">This text would be blue</H1>
<p class="myOtherClass">The text would be in red</P>
<H3 class="myOtherClass">This is level 2 heading</H3>
<table class=myotherClass border width=100%>
<html> <head>
<td>Data 1</td><td>Data 2</td></table>
<style>
<h3>This is Level 4 Heading, without style</h3>
#para1 {
<h1>This is again Level 1 heading with default styles</h1>
text-align:center;
color:red;
}
</style> </head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the
style.</p>
</body>
</html>
CSS Box Model
• All HTML elements can be considered as boxes.
• The CSS box model is essentially a box that wraps around HTML
elements, and it consists of:
Margin - Clears an area around the border. The margin does not have a
background color, it is completely transparent
Border - A border that goes around the padding and content. The border is
affected by the background color of the box
Padding - Clears an area around the content. The padding is affected by the
background color of the box
Content - The content of the box,
where text and images appear
CSS Border
• The border property is a shorthand for the following individual border
properties: border-width, border-style (required), border-color
p { border: 5px solid red; }
Introduction to Javascript
Embedding JavaScript in HTML
• The <SCRIPT> tag <SCRIPT>
JavaScript statements …
</SCRIPT>
<html>
<head> </head>
<body>
<script type="text/javascript">
document.write("<H1>Hello World!</H1>")
</script>
</body>
</html>
for(var i=0;i<10;i++)
{
document.write(“Hello”);
}
• Variables that exist only inside a function are called Local variables
• Variables that exist throughout the script are called Global variables
Their values can be changed anytime in the code and even by other functions
Predefined Functions
• isFinite: evaluates an argument to determine if it is a finite number.
isFinite (number) //where number is the number to evaluate
String Objects
• Creating a string object:
var myString = new String(“characters”)
var myString = “fred”
• “Lincoln”.length // result = 7
• “Four score”.length // result = 10
• “One\ntwo”.length // result = 7
• “”.length // result = 0
47
String functions
• charAt(index) : returns the character at a specified position.
Eg : var str = "Hello world!";
o str.charAt(0); //returns H
o str.charAt(str.length-1)); //returns !
• concat() : joins two or more strings
stringObject.concat(stringX,stringX,...,stringX)
Eg: var str1="Hello ";
var str2="world!";
document.write(str1.concat(str2));
• indexOf () : returns the position of the first occurrence of a specified
string value in a string.
index values start their count with 0.
If no match occurs within the main string, the returned value is -1.
string.indexOf( searchString [, startIndex])
Eg : var str="Hello world, welcome";
str.indexOf("Hello"); //returns 0
str.indexOf("wor")); //returns 6
str.indexOf("e",5); //returns 14
48
String Objects
• match(regExpression) var str="rain in SPAIN is mainly in plain";
Searches for a specified value in a string var patt1=/ain/gi;
document.write(str.match(patt1));
string.match(regExpression)
• replace(regExpression, replaceString)
Replaces some characters with some other characters in a string.
string.replace( regExpression, replaceString)
Eg: var str=“Hello World";
document.write(str.replace(“World", “Everyone"));
• search(regExpression)
var str = “To be, or not to be”
Searches a string for a specified value
var regexp = /be/
Eg : var str=“Hello World"; str.relace(regexp, “exist”)
str.search("World") //returns 6
var text = "testing: 1, 2, 3"; // Sample text
var pattern = /\d+/g // Matches all instances of one or more digits
text.search(pattern) // => 9: position of first match
Eg: text.match(pattern) // => ["1", "2", "3"]: array of all matches
text.replace(pattern, "#"); // => "testing: #, #, #"
49
String functions
• split(“delimiterCharacter”[, limitInteger]) - Splits a string into array of strings
string.split(“delimiterCharacter”[, limitInteger]) Output :
zero
var str = "zero one two three four";
one
var arr = str.split(" ");
two
for(i = 0; i < str.length; i++){ document.write(“<br>” + arr[i]); }
three
var myString = “Anderson,Smith,Johnson,Washington” four
var myArray = myString.split(“,”)
var itemCount = myArray.length // result: 4
Date
• Date object allows the handling of date and time information.
All dates are in milliseconds from January 1, 1970, 00:00:00.
Dates before 1970 are invalid dates.
• There are different ways to define a new instance of the date object:
<script>
var d=new Date();
document.write(d);
</script>
Array
• An array is data structure for storing and manipulating ordered
collections of data.
• An array can be created in several ways.
Eg1: Regular: ----------------------------------------- var cars=new Array();
cars[0]="Spark";
Eg 2: Condensed: cars[1]="Volvo";
o var cars=new Array("Spark","Volvo","BMW"); cars[2]="BMW";
Eg 3: Literal:
o var cars=["Spark","Volvo","BMW"];
Eg 4: var matrix = [[1,2,3], [4,5,6], [7,8,9]];
Eg 5 : var sparseArray = [1,,,,5];
arrayObject.concat(array2)
var arrayText = myArray.join(“,”)
var a1 = new Array(1,2,3)
var a2 = new Array(“a”,”b”,”c”)
var a3 = a1.concat(a2)
// result: array with values 1,2,3,”a”,”b”,”c”
• window.open(URL,name,specs)
URL : Specifies the URL of the page to open. If no URL is specified, a new
window with about:blank is opened
Name : Specifies the target attribute or the name of the window.
Specs : comma-separated list of items.
example opens an
myWindow=window.open('','','width=200,height=100'); about:blank page in a new
myWindow.document.write("<p>This is 'myWindow'</p>"); browser window:
myWindow.focus();
59
Value Explanation
value The default value of the attribute
#REQUIRED The attribute is required
#IMPLIED The attribute is optional
#FIXED value The attribute value is fixed
Eg:
<!ATTLIST paint color (RED | YELLOW | GREEN ) “RED”>
81
<emp deptno=”D10”>
• IDREFS:
The value of this attribute consists of one or more IDREF type value,
separated by spaces.
IDREFS type declaration : <!ATTLIST seminar departments IDREFS>
<?xml version=”1.0”?>
<xdoc> Element greeting element farewell
<greeting>Hello XML</greeting>
<farewell>Goodbye HTML</farewell>
</xdoc> Text Text
The Node Object
• Represents a single node in the document tree.
A node can be an element node, an attribute node, a text node
• Node Object Properties:
Property Description
A NamedNodeMap containing the attributes of this node (if it is an
attributes
Element)
childNodes Returns a NodeList of child nodes for a node
firstChild Returns the first child of a node
lastChild Returns the last child of a node
nextSibling Returns the node immediately following a node
hasAttributes() Returns true if the specified node has any attributes, else false
hasChildNodes() Returns true if the specified node has any child nodes, else false
Why Ajax?
• Intuitive and natural user interaction
• No clicking required. Call can be triggered on any event
• Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh" user
interaction model
• Only user interface elements that contain new information are updated (fast
response)
• The rest of the user interface remains displayed as it is without
interruption (no loss of operational context)
XMLHttpRequest
• JavaScript object - XMLHttpRequest object for asynchronously
exchanging the XML data between the client and the server
• XMLHttpRequest Methods
open(“method”, “URL”, syn/asyn) : Assigns destination URL, method, mode
send(content) : Sends request including string or DOM object data
abort() : Terminates current request
getAllResponseHeaders() : Returns headers (labels + values) as a string
getResponseHeader(“header”) : Returns value of a given header
setRequestHeader(“label”,”value”) : Sets Request Headers before sending
• XMLHttpRequest Properties
Onreadystatechange : Event handler that fires at each state change
readyState values – current status of request
Status : HTTP Status returned from server: 200 = OK
responseText : get the response data as a string
responseXML : get the response data as XML data
Creating an AJAX application
• Step 1: Get an instance of XHR object
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "AddNos.jsp");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("tno1=100&tno2=200");
<?php <?php
// PHP code goes here echo "<h1>Hello from PHP</h1>";
?> ?>
<!DOCTYPE html>
<html> A PHP file normally
<body> contains HTML tags,
<h1>My first PHP page</h1> and some PHP
<?php scripting code.
echo "Hello World!";
?>
</body>
</html>
// a single-line comment
# also a single-line comment
/*
• Comments in PHP : a multiple-lines comment block
PHP supports several ways spanning multiple lines
*/
PHP Variables
• A variable starts with the $ sign, followed by the name of the variable
PHP has no command for declaring a variable. It is created the moment you
first assign a value to it. Eg: $txt = "Hello world!";
$x = 5; echo "I love $txt!";
$y = 10.5; echo "I love " . $txt . "!";
<?php
• + is pure math operator: $x = "15" + 27;
$x = 5;
echo($x); //gives 42!!
$y = 4;
echo $x + $y;
• Rules for PHP variables:
?>
Starts with the $ sign, followed by the name of the variable
Must start with a letter or the underscore character only
Can only contain alpha-numeric characters & underscores (A-z, 0-9, _ )
Are case-sensitive ($age and $AGE are different)
<?php
$x = 5; // global scope
function myTest() {
echo "<p>Variable x inside function is: $x</p>"; // x inside function gives error
$y = 10; // local scope
echo "<p>Variable y inside function is: $y</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>"; // y outside function gives error
?>
Variables Scope
• The global Keyword
used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
PHP also stores all global variables in an array called $GLOBALS[index]. The
index holds the name of the variable. This array is also accessible from within
functions and can be used to update global variables directly
Variables Scope
• The static Keyword
Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted.
We need it for a further job.
To do this, use the static keyword when you first declare the variable
<?php
function myTest() {
static $x = 0;
echo $x; Note: The variable is still local
$x++; to the function.
}
Outputs : 0 1 2
myTest();
myTest();
myTest();
?>
Output data to the screen
• There are two basic ways to get output: echo and print
• print_r() and var_dump() : dumps out PHP data - it is used mostly for
debugging
$stuff = array("name" => "Chuck", "course" => "SI664");
print_r($stuff);
Data Types
• PHP supports the following data types:
String Eg - $x = "Hello world!";
Integer Eg - $x = 5985;
Float (floating point numbers - also called double) Eg $x = 10.365;
Boolean Eg - $x = true;
Array Eg - $cars = array("Volvo","BMW","Toyota");
Object
NULL
Resource : are special variables that hold references to resources external to
PHP (such as database connections)
Example:
$handle = fopen("note.txt", "r"); $s1 = "";
var_dump($handle); $v1 = null;
$bool = false;
$no1 = 1;
• gettype(): Get the type of a variable echo ('$s1 : ' . gettype($s1) . "<br>");
echo ('$v1 : ' . gettype($v1) . "<br>");
echo ('$bool : ' . gettype($bool) . "<br>");
echo ('$no1 : ' . gettype($no1) . "<br>");
PHP Constants
• A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
• To create a constant, use the define() function.
Syntax : define(name, value, case-insensitive) //case: Default is false
• Constants are automatically global & can be used across the entire script
•
PHP Operators
• Arithmetic Operators
• Assignment Operators • Logical Operators
Operator Example Result Operator Example Meaning Operator Meaning
+ 4+2 6 += y += x y=y+x || or
- 4-2 2 -= y -= x y=y-x && and
* 4*2 8 *= y *= x y=y*x and and
/ 4/2 2 /= y /= x y=y/x or or
% 4%2 0 %= y %= x y = y % x xor xor
++ x = 4; x++; x=5 ! not
-- x = 4; x--; x=3
• Comparison Operators
• String Operators
Operator Meaning
Operator Example Result == is equal to
. $txt1 . $txt2 Concatenation of $txt1 & $txt2 != is not equal to
.= $txt1 .= $txt2 Appends $txt2 to $txt1 > is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
Conditional Statements : syntax
Conditional Statements : examples
Loops : syntax
• Variable Parameters: PHP provides three functions you can use in the
function to retrieve the parameters passed to it.
func_get_args() returns an array of all parameters provided to the function;
func_num_args() returns the number of parameters provided to the function;
func_get_arg() returns a specific argument from the parameters.
$array = func_get_args();
$count = func_num_args();
$value = func_get_arg(argument_number);
PHP include
• INCLUDE appends the code from an external file into the current file.
Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website
Syntax : INCLUDE ("external_file_name");
Indexed Arrays
Associative Arrays
Multidimensional array Name Stock Sold
Volvo 22 18
• A multidimensional array is an array containing
BMW 15 13
one or more arrays
Saab 5 2
Can be two, three, four, five, or more levels deep.
Land Rover 17 15
$cars = array( Table for
array("Volvo",22,18), this data data
array("BMW",15,13), Volvo: In stock: 22, sold: 18.
array("Saab",5,2), BMW: In stock: 15, sold: 13.
array("Land Rover",17,15) Saab: In stock: 5, sold: 2.
); Land Rover: In stock: 17, sold: 15. output
$date=date_create("2013-03-15");
print_r($date);
//DateTime Object ( [date] => 2013-03-15 00:00:00.000000 [timezone_type] => 3
[timezone] => Europe/Berlin )
echo date_format($date,"Y/m/d H:i:s"); //2013/03/15 00:00:00
• $_GET: used to collect form data after submitting an HTML form with
method="get“
<body>
<a href="test_get.php?fname=Anil&lname=Patil">Test $GET</a>
</body>
Mainpage.php
<body>
<?php echo "Study " . $_GET[‘fname'] . " at " . $_GET[‘lname']; ?>
test_get.php </body>
Form Handling ($_POST)
$_REQUEST
• Used to collect data after submitting an HTML form
Form Validation
• Isset() : Determine if a variable is set and is not NULL
The isset() function returns TRUE, $s1 = isset($name); // $s1 is false
if the variable inside parentheses is set $name = "Fred";
$s2 = isset($name); // $s2 is true
Advanced form handling
• Multivalued Parameters in select element:
• HTML’s select tag allows multiple selections
To process such multiple selection, you need to make the name of the field in
the HTML form end with []. Eg:
Now, when the user submits the form, $_GET['languages'] contains an array
instead of a simple string.
This array contains the values that were selected by the user.
Advanced form handling
• Multivalued Parameters in checkbox element
Advanced form handling
• Working with radio buttons
PHP Session
• A session is a way to store information (in variables) to be used across
multiple pages.
session_start() : starts a session
o The session_start() function first checks for an existing session ID.
o If it finds one, i.e. if the session is already started, it sets up the session variables and
if doesn't, it starts a new session by creating a new session ID.
• Session variables are set as key-value pairs with the global variable:
$_SESSION
The stored data can be accessed during lifetime of a session
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
SessionExample2.php
Another Session Demo
E-mail With PHP
• Server side scripting language must provide a way of sending e-mail
from the server and, in particular, to take form input and output it to an
e-mail address
• mail($to,$subject,$body[,$headers]); - for sending mail
$to = “abc@gmail.com";
$subject = "Hi There!";
$body = "PHP is one of the best scripting languages around";
$headers = "From: xyz@gmail.com\n";
mail($to,$subject,$body,$headers);
Cookies
• setcookie(cookie-name,cookie-value): instructs the browser to save a
cookie
setcookie(name, value, expire, path, domain, secure);
setcookie() goes via response header, which means that it has to be called
before any output is made to the browser (including text, HTML etc)
o The value you set can't be read until next time the page is loaded, ie you can't save a
cookie and read the value in the same page execution
Eg : setcookie("user_name", "John Doe"); //cookie expires when session ends
Eg : setcookie("age", "36", time()+3600); //cookie expires after 1 hour
• The value can be retrieved again by using the $_COOKIE superglobal
Eg : echo $_COOKIE["user_name"];
• To delete a cookie, use the setcookie() function with an expiration date in
the past
Eg : setcookie("user", "", time() - 3600); //set expiration date to one hour ago
Cookie Demo
cookieSetExample.php
cookieGetExample.php
File handling (read)
• File handling is an important part of any web application. You often need to
open and process a file for different tasks.
PHP has several functions for creating, reading, uploading, and editing files
readfile(filename): reads a file and writes it to the output buffer
o is useful if all you want to do is open up a file and read its contents
fopen(filename,mode) : similar to readfile(), but gives more options
o If an attempt to open a file fails then fopen returns a value of false otherwise it returns
a file pointer which is used for further reading or writing to that file.
Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If
a
files does not exist then it attempts to create a file.
Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end
a+
of the file. If files does not exist then it attempts to create a file.
File handling (read)
filesize(filename) : returns file length in bytes
fread(filepointer, length of file) : read a file that is opened with fopen()
fclose(filepointer) : close the file
<?php
$filename = "sample.txt";
$fileptr = fopen( $filename, "r" );
if( $fileptr == false ) {
echo ( "Error in opening file" ); exit();
}
$filesize = filesize( $filename );
$filetext = fread( $fileptr, $filesize );
fclose( $fileptr );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
File handling (read)
• file_get_contents() : reads file contents into a string
$dataStr = file_get_contents($filename);
echo $dataStr;
emp.csv
Output – reads
a single line
readCSV.php
Array ( [0] => 1001 [1] => Harry [2] => Accts )
Array ( [0] => 1002 [1] => Jerry [2] => Sales )
while(! feof($file)) {
Array ( [0] => 1003 [1] => Tom [2] => Mktg )
print_r(fgetcsv($file));
} Reads all lines
Output
from csv file
File handling : CSV (Comma Separated Values) files
• update or write to a CSV file using the function fputcsv()
Using the die() function
<?php Warning: fopen(welcome.txt) [function.fopen]: failed to
$file=fopen("welcome.txt","r"); open stream:
?> //if file does not exist? --- No such file or directory in C:\webfolder\test.php on
line 2
<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
Databases
Steps to perform DB operations
• Step-1: Open a Connection using MySQLi procedural
mysqli_connect(host,[username][,password][,dbname])
Upon success it returns an identifier to the server; otherwise, FALSE
db4-getConn.php
db5-InsertRow.php
Steps to perform DB operations
• Step-4b : Insert multiple records into table
mysqli_multi_query(connection,query) : Perform multiple queries against the
database
Steps to perform DB operations
Steps to perform DB operations
• Step-5 : Fetching result
• Other ways of fetching result:
mysqli_fetch_all(result,resulttype) : fetches all result rows and returns the
result-set as an associative array, a numeric array, or both.
<body>
<div class="container">
<h1>Container</h1>
<p>container content</p>
</div>
</body>
Bootstrap Grid System
• Bootstrap grid system allows to properly house the website's content.
Grid system divides the screen into columns―up to 12 in each row.
The column widths vary according to the size of screen they're displayed in.
Hence, Bootstrap's grid system is responsive, as the columns resize
themselves dynamically when the size of browser window changes.
Page Components
• Page components form the basic structure of a web page.
Examples include page headers, standout panels for displaying important info,
nested comments sections, image thumbnails, and stacked lists of links
• Page Headers :
Eliminates efforts to neatly display a title with cleared browser default styles,
the proper amount of spacing around it, and a small subtitle beside it
To add a subtitle beside the title of the page, you can put it inside the same
<h1> tag that we used before; wrap the subtitle inside a <small></small> tag
Page Components : Panels
• Panels are used to display text/images within a box with rounded corners.
The panel div is divided into three parts: the panel-head, panel-body, and panel-
footer. Each of these panel parts is optional.
We can also apply various colors to each list item by adding list-group-item-*
classes along with list-group-item.
Navigation Components : Navs
• Navs are a group of links that are placed inline with each other for navigation
There are options to make this group of links appear either as tabs or small
buttons, the latter known as pills in Bootstrap.
To create tab-like navigation links:
Next, we'll use a div with class container-fluid inside this navbar element.
<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developing responsive, mobile-first projects on the web.</p>
</div>
images
• To add images on the webpage use element <img> , it has three
classes to apply simple styles to images.
.img-rounded : To add rounded corners around the edges of the image,
radius of the border is 6px.
.img-circle : To create a circle of radius is 500px
.img-thumbnail : To add some padding with grey border , making the image
look like a polaroid photo.