0% found this document useful (0 votes)
110 views

ITWS02

JavaScript is a dynamic computer programming language commonly used in web pages to interact with users. It was originally named LiveScript but renamed to JavaScript. The core language is standardized in ECMA-262. JavaScript can validate user input before submitting to servers, provide immediate feedback, and create rich interfaces.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

ITWS02

JavaScript is a dynamic computer programming language commonly used in web pages to interact with users. It was originally named LiveScript but renamed to JavaScript. The core language is standardized in ECMA-262. JavaScript can validate user input before submitting to servers, provide immediate feedback, and create rich interfaces.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 330

IT-WS02

Web Systems and


Technologies 2
Marvin DG. Garcia, MSIT
What is JavaScript?
JavaScript is a dynamic computer programming
language. It is lightweight and most commonly
used as a part of web pages, whose
implementations allow client-side script to interact
with the user and make dynamic pages. It is an
interpreted programming language with object-
oriented capabilities.

NEUST.SIC. Web Systems and Technologies 2. 2023


What is JavaScript?
JavaScript was first known as LiveScript, but
Netscape changed its name to JavaScript,
possibly because of the excitement being
generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name
LiveScript. The general-purpose core of the
language has been embedded in Netscape,
Internet Explorer, and other web browsers.

NEUST.SIC. Web Systems and Technologies 2. 2023


What is JavaScript?
The ECMA-262 Specification defined a standard
version of the core JavaScript language.
• JavaScript is a lightweight, interpreted
programming language.
• Designed for creating network-centric
applications.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform.
NEUST.SIC. Web Systems and Technologies 2. 2023
Client-Side JavaScript
Client-side JavaScript is the most common form of
the language. The script should be included in or
referenced by an HTML document for the code to
be interpreted by the browser.

It means that a web page need not be a static


HTML, but can include programs that interact with
the user, control the browser, and dynamically
create HTML content.
NEUST.SIC. Web Systems and Technologies 2. 2023
Client-Side JavaScript
The JavaScript client-side mechanism provides
many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to
check if the user has entered a valid e-mail
address in a form field.

NEUST.SIC. Web Systems and Technologies 2. 2023


Client-Side JavaScript
The JavaScript code is executed when the user
submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated


events such as button clicks, link navigation, and
other actions that the user initiates explicitly or
implicitly.

NEUST.SIC. Web Systems and Technologies 2. 2023


Advantages of JavaScript
The merits of using JavaScript are:
• Less server interaction. You can validate user
input before sending the page off to the server.
This saves server traffic, which means less load
on your server.
• Immediate feedback to the visitors. They don't
have to wait for a page reload to see if they
have forgotten to enter something.

NEUST.SIC. Web Systems and Technologies 2. 2023


Advantages of JavaScript
• Increased interactivity. You can create
interfaces that react when the user hovers over
them with a mouse or activates them via the
keyboard.
• Richer interfaces. You can use JavaScript to
include such items as drag-and-drop
components and sliders to give a Rich Interface
to your site visitors.

NEUST.SIC. Web Systems and Technologies 2. 2023


Limitations of JavaScript
JavaScript is not a programming language
because of the following:
• Client-side JavaScript does not allow the
reading or writing of files. This has been kept for
security reasons.
• JavaScript cannot be used for networking
applications because there is no such support
available.

NEUST.SIC. Web Systems and Technologies 2. 2023


Limitations of JavaScript
• JavaScript doesn’t have any multithreading or
multiprocessor capabilities.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Syntax
JavaScript can be implemented using JavaScript
statements that are placed within <script>…
</script> HTML tags in a web page.

Place the <script> tags, containing JavaScript,


anywhere within the web page, but it is normally
recommended that it should be within the <head>
tags.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Syntax
The script tag takes two important attributes:
• Language: This attribute specifies what scripting
language to be used. Typically, its value will be
JavaScript.
• Type: This attribute is what is now
recommended to indicate the scripting
language in use and its value should be set to
"text/javascript".

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Syntax
<html>
<body>
<script language="javascript"
type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Syntax
Whitespace and Line Breaks. JavaScript ignores
spaces, tabs, and newlines that appear in
JavaScript programs. Use spaces, tabs, and
newlines freely in a program and are free to
format and indent programs in a neat and
consistent way that makes the code easy to read
and understand.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Syntax
Semicolons are Optional. Simple statements in
JavaScript are generally followed by a semicolon
character, just as they are in C, C++, and Java.
JavaScript omits semicolon if each statements are
placed on a separate line. But when formatted in a
single line, use semicolons.

Note: It is a good practice to use semicolons.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Syntax
Comments in JavaScript. JavaScript supports
both C-style and C++-style comments. Thus:
• Any text between a // and the end of a line is
treated as a comment and is ignored by
JavaScript.
• Any text between the characters /* and */ is
treated as a comment. This may span multiple
lines.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Syntax
• JavaScript also recognizes the HTML comment
opening sequence <!--.JavaScript treats this as
a single-line comment, just as it does the //
comment.
• The HTML comment closing sequence --> is not
recognized by JavaScript so it should be written
as //-->.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Placement
There is a flexibility given to include JavaScript
code anywhere in an HTML document. However the
most preferred ways to include JavaScript in an
HTML file are as follows:
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head>
sections.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Placement
• Script in an external file and then include in
<head>...</head> section.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Variables
One of the most fundamental characteristics of a
programming language is the set of data types it
supports. These are the type of values that can be
represented and manipulated in a programming
language. JavaScript allows to work with three
primitive data types:
• Numbers, e.g., 123, 120.50 etc.
• Strings of text, e.g. "This text string" etc.
• Boolean, e.g. true or false.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Variables
Like many other programming languages,
JavaScript has variables. Variables can be thought
of as named containers. You can place data into
these containers and then refer to the data simply
by naming the container.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Variables
Before using a variable in a JavaScript program, it
must declared first. Variables are declared with the
var keyword as follows:

<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Variables
Variables can also be declared multiple times with
the same var keyword as follows:

<script type="text/javascript">
<!--
var money, name;
//-->
</script>

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Variables
Storing a value in a variable is called variable
initialization. A variable initialization can be done
at the time of variable creation or at a later point
in time when the variable is needed.
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script> NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Variables
The scope of a variable is the region of the
program in which it is defined. JavaScript variables
have only two scopes:
• Global Variables: A global variable has global
scope which means it can be defined anywhere
in your JavaScript code.
• Local Variables: A local variable will be visible
only within a function where it is defined.
Function parameters are always local to that
function. NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Variables
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global
variable
function checkscope( ) {
var myVar = "local"; // Declare a
local variable
document.write(myVar);
}
//-->
</script>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Variables
Variable Names. While naming your variables in
JavaScript, keep the following rules in mind:
• Do not use any of the JavaScript reserved
keywords as a variable name. For example,
break or boolean variable names are not valid.
• JavaScript variable names should not start with
a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test
is invalid, but _123test is a valid one.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Variables
• JavaScript variable names are case-sensitive.
For example, Name and name are two different
variables.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Variables
JavaScript Reserved Words.
A list of all the reserved words in JavaScript are
given in the following table. They cannot be used
as JavaScript variables, functions, methods, loop
labels, or any object names.

NEUST.SIC. Web Systems and Technologies 2. 2023


Quiz No. 1
JavaScript Operators
In the expression:

4+5=9

The 4 and 5 are called operands and the ‘+’ sign is


called the operator.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators
JavaScript supports the following types of
operators:

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators
Arithmetic Operators. An arithmetic operators
takes numerical values (either literals or variables)
as their operands and returns a single numerical
value. The standard arithmetic operators are
addition (+), subtraction (-), multiplication (*), and
division (/). These operators work as they do in
most other programming languages when used in
floating points.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators

Operator Description Example


Returns the integer remainder of dividing the
Remainder (%) 12 % 5 returns 2
two operands
If x is 3,
Adds one to its operand. If used as a prefix
then ++x sets x to 4 and
(++x), returns the value of its operand after
returns 4,
Increment (++) adding one. If used as a postfix operator (x++),
whereas x++ returns 3
returns the value of its operand before adding
and, only then, sets x to
one.
4.
If x is 3, then --x sets x to
Subtracts one from its operand. The return 2 and returns 2,
Decrement (--) value is analogous to that for the increment whereas x-- returns 3
operator. and, only then, sets x to
2.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators

Operator Description Example


Exponentiation Calculates the base to the exponent power, 2 ** 3 returns 8.
Operator (**) that is, base^exponent 10 ** -1 returns 0.1.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators
Comparison Operators. A comparison operator
compares its operands and returns a logical value
based on whether the comparison is true. The
operands can be numerical, string, logical,
or object values.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators

Operator Description Example


3 == var1
Equal (==) Returns true if the operands are equal. "3" == var1
3 == '3'
var1 != 4
Not equal (!=) Returns true if the operands are not equal.
var2 != "3"
Returns true if the left operand is greater than var2 > var1
Greater than (>)
the right operand. "12" > 2
Greater than or Returns true if the left operand is greater than var2 >= var1
equal (>=) or equal to the right operand. var1 >= 3
Returns true if the left operand is less than the var1 < var2
Less than (<)
right operand. "2" < 12
Less than or Returns true if the left operand is less than or var1 <= var2
equal (<=) equal to the right operand. var2 <= 5
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript Operators
Logical Operators. Logical operators perform
logical operations and return a boolean value,
either true or false.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators

Operator Description Example


Logical AND true if both the operands are true, else returns
x && y
(&&) false
true if either of the operands is true; returns
Logical OR (||) x || y
false if both are false
Logical NOT true if the operand is false and vice-versa. !x

NEUST.SIC. Web Systems and Technologies 2. 2023


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

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript Operators

Operator Name Example


= Assignment operator a = 7; // 7
+= Addition assignment a += 5; // a = a + 5
-= Subtraction Assignment a -= 2; // a = a – 2
*= Multiplication Assignment a *= 3; // a = a * 3
/= Division Assignment a /= 2; // a = a / 2
%= Remainder Assignment a %= 2; // a = a % 2
**= Exponentiation Assignment a **= 2; // a = a**2

NEUST.SIC. Web Systems and Technologies 2. 2023


Lab 1
JavaScript – if … else Statement
The JavaScript if-else statement is used to
execute the code whether condition is true or false.
There are three forms of if statement in JavaScript:
• If Statement
• If else statement
• If else if statement

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – if … else Statement
If statement. It evaluates the content only if
expression is true. The syntax for if statement is the
following:

if (expression) {
Statement(s) to be executed if expression is
true
}

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;

if( age > 18 ) {


document.write("<b>Qualifies for
driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then
try...</p>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – if … else Statement
If else statement. The 'if...else' statement is the next
form of control statement that allows JavaScript to
execute statements in a more controlled way.

if (expression) {
Statement(s) to be executed if expression is
true
} else {
Statement(s) to be executed if expression is
false
} NEUST.SIC. Web Systems and Technologies 2. 2023
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for
driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – if … else Statement
If else if statement. The if...else if... statement is an
advanced form of if…else that allows JavaScript to
make a correct decision out of several conditions

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – if … else Statement
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Switch
The JavaScript switch statement is used to
execute one code from multiple expressions. It is
just like else if statement but it is convenient
than if..else..if because it can be used with
numbers, characters etc.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Switch

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Switch
The objective of a switch statement is to give an
expression to evaluate and several different
statements to execute based on the value of the
expression. The interpreter checks
each case against the value of the expression until
a match is found. If nothing matches,
a default condition will be used.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Switch
switch (expression) {
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...

case condition n: statement(s)


break;

default: statement(s)
}
NEUST.SIC. Web Systems and Technologies 2. 2023
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;

case 'B': document.write("Pretty good<br />");


break;

case 'C': document.write("Passed<br />");


break;

case 'D': document.write("Not so good<br />");


break;

case 'F': document.write("Failed<br />");


break;

default: document.write("Unknown grade<br />")


}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
Lab 2
JavaScript – The While Loop
The purpose of a while loop is to execute a
statement or code block repeatedly as long as
an expression is true. Once the expression
becomes false, the loop terminates.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – The While Loop

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – The While Loop
The syntax are as follows:

while (expression) {
Statement(s) to be executed if expression is
true
}

NEUST.SIC. Web Systems and Technologies 2. 2023


while (i < 10) {
text += "The number is " + i;
i++;
}

NEUST.SIC. Web Systems and Technologies 2. 2023


// program to find the sum of positive numbers
// if the user enters a negative numbers, the loop ends
// the negative number entered is not added to sum

let sum = 0;

// take input from the user


let number = parseInt(prompt('Enter a number: '));

while(number >= 0) {

// add all positive numbers


sum += number;

// take input again if the number is positive


number = parseInt(prompt('Enter a number: '));
}

// display the sum


console.log(`The sum is ${sum}.`);
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – The While Loop
In programming, loops are used to repeat a block
of code.

The for loop is the most compact form of looping.


It includes the following three important parts:

• The loop initialization where we initialize our


counter to a starting value. The initialization
statement is executed before the loop begins.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – The For Loop
• The test statement which will test if a given
condition is true or not. If the condition is true,
then the code given inside the loop will be
executed, otherwise the control will come out of
the loop.
• The iteration statement for the increase or
decrease of the counter.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – The For Loop

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – The For Loop
The syntax of for loop is as follows:

for (initialization; test condition; iteration statement) {


Statement(s) to be executed if test condition is true
}

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – The For In Loop
The for...in loop is used to loop through an object's
properties. The syntax of for in loop is:

for (variablename in object) {


statement or block to execute
}

In each iteration, one property from object is


assigned to variablename and this loop
continues till all the properties of the object are
exhausted. NEUST.SIC. Web Systems and Technologies 2. 2023
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


Lab 3
JavaScript – Loop Control
JavaScript provides full control to handle loops
and switch statements. There may be a situation
when there is a need to come out of a loop without
reaching its bottom. There may also be a situation
to skip a part of your code block and start the next
iteration of the loop.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Loop Control
To handle all such situations, JavaScript
provides break and continue statements.
These statements are used to immediately
come out of any loop or to start the next
iteration of any loop respectively.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Loop Control
The break statement. The break statement is
used to exit a loop early, breaking out of the
enclosing curly braces.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Loop Control

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20) {


if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Loop Control
The continue statement. The continue statement
tells the interpreter to immediately start the next
iteration of the loop and skip the remaining code
block. When a continue statement is encountered,
the program flow moves to the loop check
expression immediately and if the condition
remains true, then it starts the next iteration,
otherwise the control comes out of the loop.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10) {


x = x + 1;

if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


Quiz No. 2
JavaScript – Function
A function is a group of reusable code which can
be called anywhere in your program. This
eliminates the need of writing the same code
again and again. It helps programmers in writing
modular codes. Functions allow a programmer to
divide a big program into a number of small and
manageable functions.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Function
The most common way to define a function in
JavaScript is by using the function keyword,
followed by a unique function name, a list of
parameters (that might be empty), and a
statement block surrounded by curly braces.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Function
The basic syntax is as follows:

<script type = "text/javascript">


<!--
function functionname(parameter-list) {
statements
}
//-->
</script>

NEUST.SIC. Web Systems and Technologies 2. 2023


<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Function
Calling a Function. To invoke a function
somewhere later in the script, simply write the
name of that function.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say
Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Function
Function Parameters. There are facility to pass
different parameters while calling a function.
These passed parameters can be captured
inside the function and any manipulation can
be done over those parameters. A function can
take multiple parameters separated by comma.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value
= "Say Hello">
</form>
<p>Use different parameters inside the function and then
try...</p>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Function
The return statement. A JavaScript function can
have an optional return statement. This is
required if there is a need to return a value from a
function. This statement should be the last
statement in a function.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call
Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Events
What is an event?
JavaScript's interaction with HTML is handled
through events that occur when the user or the
browser manipulates a page.

When the page loads, it is called an event. When


the user clicks a button, that click too is an event.
Other examples include events like pressing any
key, closing a window, resizing a window, etc.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Events
Developers can use these events to execute
JavaScript coded responses, which cause buttons
to close windows, messages to be displayed to
users, data to be validated, and virtually any other
type of response imaginable.

Events are a part of the Document Object Model


(DOM) Level 3 and every HTML element contains a
set of events which can trigger JavaScript Code.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Events
onclick Event Type. This is the most frequently
used event type which occurs when a user clicks
the left button of the mouse. A validation, warning
etc., can be placed against this event type.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say
Hello" />
</form>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Events
onsubmit Event Type. Is an event that occurs
when submitting form values. A form validation
can be placed against this event type.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return
validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Events
onmouseover and onmouseout. These two event
types will help in creating nice effects with images
or even with text as well. The onmouseover event
triggers when bringing a mouse pointer over any
element and the onmouseout triggers when
moving a mouse pointer out from that element.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


Html 5 Standard Events
Attribute Value Description
Offline script Triggers when the document goes offline
Onabort script Triggers on an abort event
onafterprint script Triggers after the document is printed
onbeforeonload script Triggers before the document loads
onbeforeprint script Triggers before the document is printed
onblur script Triggers when the window loses focus

oncanplay script Triggers when media can start play, but might has
to stop for buffering

oncanplaythrough script Triggers when media can be played to the end,


without stopping for buffering
onchange script Triggers when an element changes
onclick script Triggers on a mouse click
oncontextmenu script Triggers when a context menu is triggered
ondblclick script Triggers on a mouse double-click
ondrag script Triggers when
NEUST.SIC. an Systems
Web elementand
is dragged
Technologies 2. 2023
Attribute Value Description
ondragend script Triggers at the end of a drag operation

ondragenter script Triggers when an element has been dragged to a


valid drop target

ondragleave script Triggers when an element is being dragged over a


valid drop target
ondragover script Triggers at the start of a drag operation
ondragstart script Triggers at the start of a drag operation
ondrop script Triggers when dragged element is being dropped
ondurationchange script Triggers when the length of the media is changed

onemptied script Triggers when a media resource element suddenly


becomes empty.
onended script Triggers when media has reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the window gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets user input
NEUST.SIC. Web Systems and Technologies 2. 2023
Attribute Value Description
onhaschange script Triggers when the document has change
oninput script Triggers when an element gets user input
oninvalid script Triggers when an element is invalid
onkeydown script Triggers when a key is pressed
onkeypress script Triggers when a key is pressed and released
onkeyup script Triggers when a key is released
onload script Triggers when the document loads
onloadeddata script Triggers when media data is loaded

onloadedmetadata script Triggers when the duration and other media data of
a media element is loaded

onloadstart script Triggers when the browser starts to load the media
data
onmessage script Triggers when the message is triggered
onmousedown script Triggers when a mouse button is pressed
onmousemove script Triggers when the mouse pointer moves

NEUST.SIC. Web Systems and Technologies 2. 2023


Attribute Value Description

onmouseout script Triggers when the mouse pointer moves out of an


element

onmouseover script Triggers when the mouse pointer moves over an


element
onmouseup script Triggers when a mouse button is released
onmousewheel script Triggers when the mouse wheel is being rotated
onoffline script Triggers when the document goes offline
onoine script Triggers when the document comes online
ononline script Triggers when the document comes online
onpagehide script Triggers when the window is hidden
onpageshow script Triggers when the window becomes visible
onpause script Triggers when media data is paused
onplay script Triggers when media data is going to start playing
onplaying script Triggers when media data has start playing
onpopstate script Triggers when the window's history changes

NEUST.SIC. Web Systems and Technologies 2. 2023


Attribute Value Description

onprogress script Triggers when the browser is fetching the media


data

onratechange script Triggers when the media data's playing rate has
changed
onreadystatechange script Triggers when the ready-state changes
onredo script Triggers when the document performs a redo
onresize script Triggers when the window is resized

onscroll script Triggers when an element's scrollbar is being


scrolled

onseeked script Triggers when a media element's seeking attribute is


no longer true, and the seeking has ended

onseeking script Triggers when a media element's seeking attribute is


true, and the seeking has begun
onselect script Triggers when an element is selected

onstalled script Triggers when there is an error in fetching media


data
onstorage script Triggers when a document loads
NEUST.SIC. Web Systems and Technologies 2. 2023
Attribute Value Description
onsubmit script Triggers when a form is submitted
Triggers when the browser has been fetching media
onsuspend script data, but stopped before the entire media file was
fetched
ontimeupdate script Triggers when media changes its playing position
onundo script Triggers when a document performs an undo
onunload script Triggers when the user leaves the document

onvolumechange script Triggers when media changes the volume, also


when volume is set to "mute"

onwaiting script Triggers when media has stopped playing, but is


expected to resume

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript and Cookies
What are cookies?
Web Browsers and Servers use HTTP protocol to
communicate and HTTP is a stateless protocol. But
for a commercial website, it is required to maintain
session information among different pages. For
example, one user registration ends after
completing many pages. But how to maintain
users' session information across all the web
pages.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript and Cookies
In many situations, using cookies is the most
efficient method of remembering and tracking
preferences, purchases, commissions, and other
information required for better visitor experience or
site statistics.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript and Cookies
How it works?
The server sends some data to the visitor's browser
in the form of a cookie. The browser may accept
the cookie. If it does, it is stored as a plain text
record on the visitor's hard drive. Now, when the
visitor arrives at another page on your site, the
browser sends the same cookie to the server for
retrieval. Once retrieved, your server
knows/remembers what was stored earlier.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript and Cookies
Cookies are a plain text data record of 5 variable-
length fields:
• Expires. The date the cookie will expire. If this is
blank, the cookie will expire when the visitor quits
the browser.
• Domain. The domain name of the site.
• Path − The path to the directory or web page
that set the cookie. This may be blank for the
retrieval of cookie from any directory or page.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript and Cookies
• Secure. If this field contains the word "secure",
then the cookie may only be retrieved with a
secure server. If this field is blank, no such
restriction exists.
• Name=Value. Cookies are set and retrieved in
the form of key-value pairs

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Dialog Boxes
JavaScript supports three important types of
dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input
or to have a kind of input from the users.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Dialog Boxes
Alert Dialog Box. An alert dialog box is mostly
used to give a warning message to the users.
For example, if one input field requires to enter
some text but the user does not provide any
input, then as a part of validation, use an alert
box to give a warning message.

NEUST.SIC. Web Systems and Technologies 2. 2023


JavaScript – Dialog Boxes
Nonetheless, an alert box can still be used for
friendlier messages. Alert box gives only one
button "OK" to select and proceed.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick =
"Warn();" />
</form>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Dialog Boxes
Confirmation Dialog Box. A confirmation dialog
box is mostly used to take user's consent on any
option. It displays a dialog box with two
buttons: OK and Cancel.

If the user clicks on the OK button, the window


method confirm() will return true. If the user clicks
on the Cancel button, then confirm() returns
false.
NEUST.SIC. Web Systems and Technologies 2. 2023
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Dialog Boxes
Prompt Dialog Box. The prompt dialog box is very
useful when a pop-up text box is used to get user
input. Thus, it enables interaction with the user. The
user needs to fill in the field and then click OK.

This dialog box is displayed using a method


called prompt() which takes two parameters: (i) a
label which you want to display in the text box and
(ii) a default string to display in the text box.
NEUST.SIC. Web Systems and Technologies 2. 2023
JavaScript – Dialog Boxes
This dialog box has two buttons: OK and Cancel. If
the user clicks the OK button, the window
method prompt() will return the entered value
from the text box. If the user clicks the Cancel
button, the window method prompt() returns null.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


Document Object Model or DOM
The document object represents the whole html
document.

When html document is loaded in the browser, it


becomes a document object. It is the root
element that represents the html document. It has
properties and methods. By the help of document
object, we can add dynamic content to our web
page.
NEUST.SIC. Web Systems and Technologies 2. 2023
Document Object Model or DOM
DOM is a way to represent the webpage in a
structured hierarchical way so that it will become
easier for programmers and users to glide through
the document. With DOM, accessing and
manipulating tags, IDs, classes, Attributes, or
Elements of HTML using commands or methods
provided by the Document object becomes easy.

NEUST.SIC. Web Systems and Technologies 2. 2023


Document Object Model or DOM
Using DOM, the JavaScript gets access to HTML as
well as CSS of the web page and can also add
behavior to the HTML elements. So
basically Document Object Model is an API that
represents and interacts with HTML or XML
documents.

NEUST.SIC. Web Systems and Technologies 2. 2023


Document Object Model or DOM
Properties of document object that can be
accessed and modified by the document object:

NEUST.SIC. Web Systems and Technologies 2. 2023


Document Object Model or DOM
Documents contents can be access and change
by its methods. Important methods of document
object are as follows:
Method Description
write(“string”) Writes the given string on the document
writeIn(“string”) Writes the given string on the document with newline character at the
end
getElementById() Returns the element having the given id value
getElementsByName() Returns all the elements having the given name value
getElementsByTagName() Returns all the elements having the given tag name.
getElementsByClassName() Returns all the elements having the given class name.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
The term PHP is an acronym for PHP: Hypertext
Preprocessor. PHP is a server-side scripting
language designed specifically for web
development. It is open-source which means it is
free to download and use. It is very simple to learn
and use. The files have the extension “.php”.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
Rasmus Lerdorf inspired the first version of PHP
and participated in the later versions. It is an
interpreted language and it does not require a
compiler.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
• PHP code is executed in the server.
• It can be integrated with many databases such
as Oracle, Microsoft SQL Server, MySQL,
PostgreSQL, Sybase, and Informix.
• It is powerful to hold a content management
system like WordPress and can be used to
control user access.
• It supports main protocols like HTTP Basic, HTTP
Digest, IMAP, FTP, and others.
NEUST.SIC. Web Systems and Technologies 2. 2023
Hypertext Preprocessor - PHP
• Websites like www.facebook.com and
www.yahoo.com are also built on PHP.
• One of the main reasons behind this is that PHP
can be easily embedded in HTML files and HTML
codes can also be written in a PHP file.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
• The thing that differentiates PHP from the client-
side language like HTML is, that PHP codes are
executed on the server whereas HTML codes are
directly rendered on the browser. PHP codes are
first executed on the server and then the result is
returned to the browser.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
• The only information that the client or browser
knows is the result returned after executing the
PHP script on the server and not the actual PHP
codes present in the PHP file. Also, PHP files can
support other client-side scripting languages like
CSS and JavaScript.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
PHP performs system functions, i.e. from files on a
system it can create, open, read, write, and close
them. The other uses of PHP are:
• PHP can handle forms, i.e. gather data from files,
save data to a file, thru email you can send data,
return data to the user.
• You add, delete, modify elements within your
database thru PHP.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some
pages of your website.
• It can encrypt data.

NEUST.SIC. Web Systems and Technologies 2. 2023


Hypertext Preprocessor - PHP
Characteristics of PHP
Five important characteristics make PHPs practical
nature possible:
• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
Escaping to PHP
The PHP parsing engine needs a way to
differentiate PHP code from other elements in the
page. The mechanism for doing so is known as
'escaping to PHP.' There are four ways to do the
escaping.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
Canonical PHP tags
The most universally effective PHP tag style is:

<?php
...
?>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
Short-open (SGML-style) tags
Short or short-open tags look like this:

<?
...
?>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
ASP-style tags
ASP-style tags mimic the tags used by Active
Server Pages to delineate code blocks. ASP-style
tags look like this:

<%
...
%>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
HTML script tags
HTML script tags look like this:

<script language=“PHP”>
...
</script>

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php echo "Hello, World! This
is PHP code";?>
</body>
</html>
PHP Syntax
Commenting PHP code
A comment is the portion of a program that exists
only for the human reader and stripped out before
displaying the programs result. There are two
commenting formats in PHP:

Single-line comments. They are generally used for


short explanations or notes relevant to the local
code.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Syntax
<?
# This is a comment, and
# This is the second line of the
comment
// This is a comment too. Each style
comments only
print "An example with single line
comments";
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Syntax
Multi-lines comments. They are generally used to
provide pseudocode algorithms and more
detailed explanations when necessary. The
multiline style of commenting is the same as in C.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
<?
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line
comments";
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Syntax
Whitespace insensitive. Whitespace is the stuff
you type that is typically invisible on the screen,
including spaces, tabs, and carriage returns (end-
of-line characters). PHP whitespace insensitive
means that it almost never matters how many
whitespace characters you have in a row.one
whitespace character is the same as many such
characters.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
$four = 2 + 2; // single spaces
$four <tab>=<tab2<tab>+<tab>2 ; // spaces
and tabs
$four =
2+
2; // multiple lines

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
PHP is case sensitive. Like any other languages,
PHP is a case sensitive language. Variables Num
and num are different.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
<html>
<body>
<?
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Syntax
Statements are expressions terminated by
semicolons. A statement in PHP is any expression
that is followed by a semicolon (;).Any sequence of
valid PHP statements that is enclosed by the PHP
tags is a valid PHP program.

$greeting = "Welcome to PHP!";

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
Expressions are combinations of tokens. The
smallest building blocks of PHP are the indivisible
tokens, such as numbers (3.14159), strings (.two.),
variables ($two), constants (TRUE), and the special
words that make up the syntax of PHP itself like if,
else, while, for and so forth

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
Braces make blocks. The smallest building blocks
of PHP are the indivisible tokens, such as numbers
(3.14159), strings (.two.), variables ($two), constants
(TRUE), and the special words that make up the
syntax of PHP itself like if, else, while, for and so
forth.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Syntax
if (3 == 2 + 1)
print("Good - I haven't totally lost my
mind.<br>");
if (3 == 2 + 1)
{
print("Good - I haven't totally");
print("lost my mind.<br>");
}

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
The main way to store information in the middle of
a PHP program is by using a variable. Here are the
most important things to know about variables in
PHP.
• All variables in PHP are denoted with a leading
dollar sign ($).
• The value of a variable is the value of its most
recent assignment.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
• Variables are assigned with the = operator, with
the variable on the left-hand side and the
expression to be evaluated on the right.
• Variables can, but do not need, to be declared
before assignment.
• Variables in PHP do not have intrinsic types - a
variable does not know in advance whether it
will be used to store a number or a string of
characters.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
• Variables used before they are assigned have
default values.
• PHP does a good job of automatically converting
types from one to another when necessary.
• PHP variables are Perl-like.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
Integers. They are whole numbers, without a
decimal point, like 4195. They are the simplest type
of PHP data types. They correspond to simple
whole numbers, both positive and negative.
Integers can be assigned to variables, or they can
be used in expressions

$int_var = 12345;
$another_int = -12345 + 12345;
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
Doubles. They are numbers with decimals. By
default, doubles print with the minimum number of
decimal places needed.

$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
Boolean. They have only two possible values either
true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE,
which can be used like:

if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
Null. NULL is a special type that only has one value:
NULL. To give a variable the NULL value, simply
assign it like this:

$my_var = NULL;

The special constant NULL is capitalized by


convention, but actually it is case insensitive.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
Strings. They are sequences of characters, like "PHP
supports string operations". Following are valid
examples of string:
$string_1 = "This is a string in double
quotes";
$string_2 = ‘This is a somewhat longer,
singly quoted string’;
$string_0 = ""; // a string with zero
characters
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
Singly quoted strings are treated almost literally,
whereas doubly quoted strings replace variables
with their values as well as specially interpreting
certain character sequences.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
<?
$variable = "name";
$literally = 'My $variable will not
print!\\n’;
print($literally);
$literally = "My $variable will
print!\\n";
print($literally);
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
There are no artificial limits on string length - within
the bounds of available memory, you ought to be
able to make arbitrarily long strings. Strings that
are delimited by double quotes (as in "this") are
preprocessed in both the following two ways by
PHP:
• Certain character sequences beginning with
backslash (\) are replaced with special
characters
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
• Variable names (starting with $) are replaced
with string representations of their values.
The escape-sequence replacements
\n Replaced by the new line character
\r Replaced by the carriage-return character
\t Replaced by the tab character
\$ Replaced by the dollar sign itself ($)
\” Replaced by a single double quote (“)
\\ Replaced by a single backslash (\)
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
Variable Naming. Rules for naming a variable:
• Variable names must begin with a letter or
underscore character.

• A variable name can consist of numbers, letters,


underscores but you cannot use characters like
+ , - , % , ( , ) . & , etc

There is no size limit for variables.


NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
Scope can be defined as the range of availability a
variable has to the program in which it is declared.
PHP variables can be one of four scope types:
• Local variables. A variable declared in a function
is considered local; that is, it can be referenced
solely in that function. Any assignment outside of
that function will be considered to be an entirely
different variable from the one contained in the
function.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
<?
$x = 4;
function assignx ()
{
$x = 0;
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
• Function Parameters. Function parameters are
declared after the function name and inside
parentheses. They are declared much like a
typical variable.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
<?
// multiply a value by 10 and return it to
the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Variable Types
• Global Variables. A global variable can be
accessed in any part of the program. However, in
order to be modified, a global variable must be
explicitly declared to be global in the function in
which it is to be modified. This is accomplished,
conveniently enough, by placing the keyword
GLOBAL in front of the variable that should be
recognized as global.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
Placing this keyword in front of an already existing
variable tells PHP to use the variable having that
name.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
• Static Variables. In contrast to the variables
declared as function parameters, which are
destroyed on the function's exit, a static variable
will not lose its value when the function exits and
will still hold that value should the function be
called again. You can declare a variable to be
static simply by placing the keyword STATIC in
front of the variable name.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Variable Types
<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Constants
A constant is a name or an identifier for a simple
value. A constant value cannot change during the
execution of the script. By default, a constant is
case-sensitive. By convention, constant identifiers
are always uppercase. A constant name starts with
a letter or underscore, followed by any number of
letters, numbers, or underscores.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Constants
To define a constant, use define() function and to
retrieve the value of a constant, simply specify its
name. Unlike with variables, constants do not need
to start with a $ sign. The function constant() can
also read a constant's value.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Constants
constant(). As indicated by the name, this function
will return the value of the constant.
This is useful in retrieving value of a constant. It is
stored in a variable or returned by a function.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Constants

<?php
define("MINSIZE", 50);

echo MINSIZE;
echo constant("MINSIZE"); // same
thing as the previous line
?>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Constants
Differences between constants and variable.
• There is no need to write a dollar sign ($) before
a constant, where as in Variable one has to write
a dollar sign.
• Constants cannot be defined by simple
assignment, they may only be defined using the
define() function.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Constants
• Constants may be defined and accessed
anywhere without regard to variable scoping
rules.
• Once the Constants have been set, may not be
redefined or undefined.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Constants
// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");
define("__THREE__", "third value");

// Invalid constant names


define("2TWO", "second thing");

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
PHP operators can be classified according to the
following:
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Arithmetic Operators
Operator Description Example
+ Adds two operands A+B
- Subtracts two operands A–B
* Multiply both operands A*B
/ Divide numerator by denominator A/B
Modulus Operator and remainder
% A%B
of an integer division
++ Increment Operator A++
-- Decrement Operator A--
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Operators
Comparison Operators
Operator Description Example
Checks if the value of two operands are
== equal or not, if yes then condition (A==B)
becomes true.
Checks if the value of two operands are
!= equal or not, if values are not equal then (A!=B)
condition becomes true.
Checks if the value of left operand is
> greater than the value of right operand, if (A>B)
yes then condition becomes true.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Operators
Operator Description Example
Checks if the value of left operand is less
< than the value of right operand, if yes (A<B)
then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of right
>= (A>=B)
operand, if yes then condition becomes
true.
Checks if the value of left operand is less
than or equal to the value of right
<= (A<=B)
operand, if yes then condition becomes
true.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Operators
Logical Operators
Operator Description Example
Called Logical AND operator. If
and both the operands are true then (A and B)
condition becomes true.
Called Logical OR Operator. If any
or of the two operands are non zero (A or B)
then condition becomes true.
Called Logical AND operator. If
&& both the operands are non zero (A && B)
then condition becomes true.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Operators
Operator Description Example
Called Logical OR Operator. If any
|| of the two operands are non zero (A || B)
then condition becomes true.
Called Logical NOT Operator. Use
to reverses the logical state of its
! operand. If a condition is true then !(A && B)
Logical NOT operator will make
false.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Assignment Operators
Operator Description Example
Simple assignment operator,
= Assigns values from right side A+B=C
operands to left side operand
Add AND assignment operator, It
adds right operand to the left C += A is the same
+=
operand and assign the result to as C = C + A
left operand

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Operator Description Example
Subtract AND assignment
operator, It subtracts right
C -= A is the same
-= operand from the left operand
as C = C – A
and assign the result to left
operand
Multiply AND assignment operator,
It multiplies right operand with the C *= A is the same
*=
left operand and assign the result as C = C * A
to left operand

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Operator Description Example
Divide AND assignment operator,
It divides left operand with the C /= A is the same
/=
right operand and assign the as C = C / A
result to left operand
Modulus AND assignment
operator, It takes modulus using C %= A is the same
%=
two operands and assign the as C = C % A
result to left operand

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Conditional Operators. There is one more operator
called conditional operator. This first evaluates an
expression for a true or false value and then
execute one of the two given statements
depending upon the result of the evaluation.
Operator Description Example
If Condition is true ?
?: Conditional Expression Then value X :
Otherwise value Y

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Precedence of PHP Operators. Operator
precedence determines the grouping of terms in
an expression. This affects how an expression is
evaluated. Certain operators have higher
precedence than others; for example, the
multiplication operator has higher precedence
than the addition operator

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Operators
Category Operator Associativity
Unary ! ++ -- Right to Left
Multiplicative */% Left to Right
Additive +- Left to Right
Relational < <= > >= Left to Right
Equality == != Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Left to Right
Assoignment = += -= *= /= %= Left to Right

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
The if, elseif ...else and switch statements are
used to take decision based on the different
condition. Use conditional statements in codes
to make decisions. PHP supports following three
decision making statements:
• If … else statement
• Elseif statement
• Switch statement
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Decision Making
If… Else Statement. Use this statement to execute a
set of code when a condition is true and another if
the condition is not true

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>

<?php
$d = date("D");

if ($d == "Fri")
echo "Have a nice weekend!";

else
echo "Have a nice day!";
?>

</body>
</html>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Decision Making
ElseIf Statement. Is used with the if...else statement
to execute a set of code if one of the several
condition is true.

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;
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Decision Making
<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>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Decision Making
Switch Statement. Is used to select one of many
blocks of code to be executed. The switch
statement is used to avoid long blocks of
if..elseif..else code.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
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;
}

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Loop Types
Loops in PHP are used to execute the same
block of code a specified number of times. PHP
supports following four loop types.
• For
• While
• Do…while
• Foreach

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
For Loop Statement. Loops through a block of
code a specified number of times.

for (initialization; condition;


increment)
{
code to be executed;
}

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>
<?php
$a = 0;
$b = 0;

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


$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b = $b" );


?>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
While Loop Statement. Loops through a block of
code if and as long as a specified condition is
true.

while (condition) {
code to be executed;
}

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>
<?php
$i = 0;
$num = 50;

while( $i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );


?>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
Do…While Loop Statement. Loops through a
block of code once, and then repeats the loop as
long as a special condition is true.

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

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>
<?php
$i = 0;
$num = 0;

do {
$i++;
}

while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
ForEach Loop Statement. Loops through a block
of code for each element in an array.

foreach (array as value) {


code to be executed;
}

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
Break Statement. The PHP break keyword is used
to terminate the execution of a loop prematurely.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>

<?php
$i = 0;

while( $i < 10) {


$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>

</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
Continue Statement. The PHP continue keyword
is used to halt the current iteration of a loop but it
does not terminate the loop.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Decision Making
<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>

</body>
</html>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Arrays
An array is a data structure that stores one or
more similar type of values in a single value.
There are three different kind of arrays and each
array value is accessed using an ID c which is
called array index.

• Numeric Array
• Associative Array
• Multidimensional Array
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Arrays
Numeric Array. These arrays can store numbers,
strings and any object but their index will be
represented by numbers. By default array index
starts from zero.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>
</body>
</html>
PHP Arrays
Associative Array. The associative arrays are very
similar to numeric arrays in term of functionality
but they are different in terms of their index.
Associative array will have their index as string so
that it can establish a strong association between
key and values.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>
PHP Arrays
Multidimensional Array. A multi-dimensional
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. Values in the multi-
dimensional array are accessed using multiple
index.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>

<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>
PHP Strings
They are sequences of characters, like "PHP
supports string operations". The following are
valid strings:

$string_1 = "This is a string in double quotes";


$string_2 = "This is a somewhat longer, singly quoted
string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Strings
Singly quoted strings are treated almost literally,
whereas doubly quoted strings replace variables
with their values as well as specially interpreting
certain character sequences.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Strings
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';

print($literally);
print "<br />";

$literally = "My $variable will print!\\n";

print($literally);
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Strings
There are no artificial limits on string length -
within the bounds of available memory, you
ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in
"this") are preprocessed in both the following two
ways by PHP:
• Certain character sequences beginning with
backslash (\) are replaced with special
characters
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Strings
• Variable names (starting with $) are replaced
with string representations of their values.

The escape-sequence replacements are:


• \n is replaced by the newline character
• \r is replaced by the carriage-return
character
• \t is replaced by the tab character
• \$ is replaced by the dollar sign itself ($)
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Strings
• \" is replaced by a single double-quote (")
• \\ is replaced by a single backslash (\)

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Strings
String Concatenation. To concatenate two string
variables together, use the dot (.) operator.

<?php
$string1="Hello World";
$string2="1234";

echo $string1 . " " . $string2;


?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Strings
Strlen() Function. The strlen() function is used to
find the length of a string.

<?php
echo strlen("Hello world!");
?>

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Strings
Strpos() Function. The strpos() function is used to
search for a string or character within a string. If a
match is found in the string, this function will
return the position of the first match. If no match
is found, it will return FALSE.

<?php
echo strpos("Hello world!","world");
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Web Concepts
This session demonstrates how PHP can provide
dynamic content according to browser type,
randomly generated numbers or User Input. It
also demonstrated how the client browser can be
redirected.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Web Concepts
Using HTML Forms. This session demonstrates
how PHP can provide dynamic content according
to browser type, randomly generated numbers or
User Input. It also demonstrated how the client
browser can be redirected.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method =


"POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name’]
)) {
die ("invalid name and name should be
alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years
old.";

exit();
}
?>
PHP Web Concepts
Browser Redirection. The PHP header() function
supplies raw HTTP headers to the browser and
can be used to redirect it to another location. The
redirection script should be at the very top of the
page to prevent any other part of the page from
loading.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>

<p>Choose a site to visit :</p>

<form action = "<?php $_SERVER['PHP_SELF'] ?>" method ="POST">


<select name = "location">.

<option value = "http://www.tutorialspoint.com">


Tutorialspoint.com
</option>

<option value = "http://www.google.com">


Google Search Page
</option>

</select>
<input type = "submit" />
</form>

</body>
</html>
<?php
if( $_POST["location"] ) {
$location = $_POST["location"];
header( "Location:$location" );

exit();
}
?>
PHP GET and POST Methods
There are two ways the browser client can
send information to the web server.

• GET Method
• POST Method

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP GET and POST Methods
Before the browser sends the information, it
encodes it using a scheme called URL encoding.
In this scheme, name/value pairs are joined with
equal signs and different pairs are separated by
the ampersand.

name1=value1&name2=value2&name3=value3

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP GET and POST Methods
GET Method. The GET method sends the encoded
user information appended to the page request.
The page and the encoded information are
separated by the ? character.

http://www.test.com/index.htm?name1=value
1&name2=value2

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP GET and POST Methods
• The GET method produces a long string that
appears in your server logs, in the browser's
Location: box.
• The GET method is restricted to send upto 1024
characters only.
• Never use GET method if you have password or
other sensitive information to be sent to the
server.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP GET and POST Methods
• GET can't be used to send binary data, like
images or word documents, to the server.
• The data sent by GET method can be
accessed using QUERY_STRING environment
variable.
• The PHP provides $_GET associative array to
access all the sent information using GET
method.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method =


"GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years
old.";

exit();
}
?>
PHP GET and POST Methods
POST Method. The POST method transfers
information via HTTP headers. The information is
encoded as described in case of GET method
and put into a header called QUERY_STRING.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP GET and POST Methods
• The POST method does not have any restriction
on data size to be sent.
• The POST method can be used to send ASCII as
well as binary data.
• The data sent by POST method goes through
HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make
sure that your information is secure.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP GET and POST Methods
• The PHP provides $_POST associative array to
access all the sent information using POST
method.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z’-
]/",$_POST['name'] )) {
die ("invalid name and name should be
alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years
old.";

exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method =


"POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
PHP File Inclusion
A PHP file can be included into another PHP file
before the server executes it. There are two PHP
functions which can be used to include a PHP file
into another PHP file:
• The include() Function
• The require() Function

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP File Inclusion
This is a strong point of PHP which helps in
creating functions, headers, footers, or elements
that can be reused on multiple pages. This will
help developers to make it easy to change the
layout of complete website with minimal effort. If
there is any change required then instead of
changing thousand of files just change included
file.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP File Inclusion
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. If there
is any problem in loading a file then
the include() function generates a warning but
the script will continue execution.

NEUST.SIC. Web Systems and Technologies 2. 2023


<a href="http://www.tutorialspoint.com/index.htm">Home</a> -
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />
<html>
<body>

<?php include("menu.php"); ?>


<p>This is an example to show how to
include PHP file!</p>

</body>
</html>
PHP File Inclusion
The require() Function. The require() function
takes all the text in a specified file and copies it
into the file that uses the include function. If there
is any problem in loading a file then
the require() function generates a fatal error and
halt the execution of the script.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP File Inclusion
So there is no difference in require() and include()
except they handle error conditions. It is
recommended to use the require() function
instead of include(), because scripts should not
continue executing if files are missing or
misnamed.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Files and I/O
The following are related to file manipulation:
• Opening a file
• Reading a file
• Writing a file
• Closing a file

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Files and I/O
Opening and Closing Files. The
PHP fopen() function is used to open a file. It
requires two arguments stating first the file name
and then mode in which to operate.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Files and I/O
Files modes can be specified as one of the six
options in this table.
Mode Purpose
r Opens file for reading only. Places the file pointer at the
beginning of the file
r+ Opens file for reading and writing. Places the file pointer
at the beginning of the file
w Opens file for writing only. Places the file pointer at the
beginning of the file and truncates the file to zero length.
If files does not
exist then it attempts to create a file.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Files and I/O
Files modes can be specified as one of the six
options in this table.
Mode Purpose
w+ Opens file for reading and writing only. Places the file
pointer at the beginning of the file. and truncates the file
to zero length. If files does not exist then it attempts to
create a file.
a Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
a+ Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Files and I/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. After making a
changes to the opened file it is important to close
it with the fclose() function. The fclose() function
requires a file pointer as its argument and then
returns true when the closure succeeds or false if
it fails.
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Files and I/O
Reading a file. Once a file is opened
using fopen() function it can be read with a
function called fread(). This function requires two
arguments. These must be the file pointer and the
length of the file expressed in bytes.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Files and I/O
The files length can be found using
the filesize() function which takes the file name
as its argument and returns the size of the file
expressed in bytes.

NEUST.SIC. Web Systems and Technologies 2. 2023


<html>

<head>
<title>Reading a file using PHP</title>
</head>

<body>

<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "<pre>$filetext</pre>" );
?>

</body>
</html>
PHP Files and I/O
Writing a file. A new file can be written or text can
be appended to an existing file using the
PHP fwrite() function. This function requires two
arguments specifying a file pointer and the string
of data that is to be written. Optionally a third
integer argument can be included to specify the
length of the data to write. If the third argument is
included, writing would will stop after the
specified length has been reached.
NEUST.SIC. Web Systems and Technologies 2. 2023
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );

if( $file == false ) {


echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>

<head>
<title>Writing a file using PHP</title>
</head>

<body>

<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "$filetext" );
echo("file name: $filename");
?>

</body>
</html>
PHP Functions
PHP functions are similar to other programming
languages. A function is a piece of code which
takes one more input in the form of parameter
and does some processing and returns a value.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Functions
Creating a Function. Creating a function starts
with the keyword function followed by a
parenthesis. An optional parameters can be
written between the parenthesis, and all the PHP
code should be put inside the { and } braces.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice
time!";
}
/* Calling a PHP Function */
writeMessage();
?>
PHP Functions
PHP Function with Parameters. PHP gives option
to pass parameters inside a function. These
parameters work like variables inside a function.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
PHP Functions
Passing arguments by Parameters. It is possible
to pass arguments to functions by reference. This
means that a reference to the variable is
manipulated by the function rather than a copy
of the variable's value.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Functions
Any changes made to an argument in these
cases will change the value of the original
variable. You can pass an argument by reference
by adding an ampersand to the variable name in
either the function call or the function definition.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
PHP Functions
PHP Functions returning value. A function can
return a value using the return statement in
conjunction with a value or object. Return stops
the execution of the function and sends the value
back to the calling code. A return value from a
function can be more than one.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function :
$return_value";
?>
PHP Functions
Setting default values for Function parameters. A
value can be set in the function parameters if the
caller’s function does not pass it.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
PHP Functions
Dynamic Function calls. It is possible to assign
function names as strings to variables and then
treat these variables exactly as the function
name itself.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
PHP Cookies
Cookies are text files stored on the client
computer and they are kept to use for tracking
purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying
returning users:
• Server scripts sends a set of cookies to the
browser. For example name, age, or
identification number etc.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Cookies
• Browser stores this information on local
machine for future use.
• When the next time browser sends an request
to web server then it sends those cookies
information to the server and server uses that
information to identify the user.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Cookies
The anatomy of a cookie. Cookies are usually set
in an HTTP header (although JavaScript can also
set a cookie directly on a browser). A PHP script
that sets a cookie might send headers that look
something like this −

NEUST.SIC. Web Systems and Technologies 2. 2023


HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-
Feb-07 22:03:38 GMT;
path=/;
domain=tutorialspoint.com
Connection: close
Content-Type: text/html
PHP Cookies
The Set-Cookie header contains a name value
pair, a GMT date, a path and a domain. The name
and value will be URL encoded. The expires field is
an instruction to the browser to "forget" the cookie
after the given time and date.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Cookies
If the browser is configured to store cookies, it will
then keep this information until the expiry date. If
the user points the browser at any page that
matches the path and domain of the cookie, it will
resend the cookie to the server. The browser's
headers might look something like this −

NEUST.SIC. Web Systems and Technologies 2. 2023


GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I;
Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
PHP Cookies
A PHP script will then have access to the cookie in
the environmental variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds all cookie
names and values. Above cookie can be
accessed using $HTTP_COOKIE_VARS["name"].

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Cookies
Setting Cookies with PHP. PHP
provided setcookie() function to set a cookie.
This function requires up to six arguments and
should be called before <html> tag. For each
cookie this function has to be called separately.

setcookie(name, value, expire, path,


domain, security);

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Cookies
• Name − This sets the name of the cookie
and is stored in an environment variable
called HTTP_COOKIE_VARS. This variable is
used while accessing cookies.
• Value − This sets the value of the named
variable and is the content that you actually
want to store.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Cookies
• Expiry − This specify a future time in seconds
since 00:00:00 GMT on 1st Jan 1970. After this
time cookie will become inaccessible. If this
parameter is not set then cookie will
automatically expire when the Web Browser is
closed.
• Path − This specifies the directories for which
the cookie is valid. A single forward slash
character permits the cookie to be valid for all
directories. NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Cookies
• Domain − This can be used to specify the
domain name in very large domains and must
contain at least two periods to be valid. All
cookies are only valid for the host and domain
which created them.
• Security − This can be set to 1 to specify that the
cookie should only be sent by secure
transmission using HTTPS otherwise set to 0
which mean cookie can be sent by regular
HTTP. NEUST.SIC. Web Systems and Technologies 2. 2023
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>

<head>
<title>Setting Cookies with PHP</title>
</head>

<body>
<?php echo "Set Cookies"?>
</body>

</html>
PHP Cookies
Accessing Cookies with PHP. PHP provides many
ways to access cookies. Simplest way is to use
either $_COOKIE or $HTTP_COOKIE_VARS
variables.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
echo $_COOKIE["name"]. "<br />";

/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";

/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
PHP Cookies
Use isset() function to check if a cookie is set or
not.

<?php
if( isset($_COOKIE["name"]))
{
echo "Welcome " . $_COOKIE["name"] . "<br />";
}else
{
echo "Sorry... Not recognized" . "<br />";
}
?>
NEUST.SIC. Web Systems and Technologies 2. 2023
PHP Cookies
Deleting Cookies with PHP. Officially, to delete a
cookie call setcookie() with the name argument
only but this does not always work well, however,
and should not be relied on.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>

<head>
<title>Deleting Cookies with PHP</title>
</head>

<body>
<?php echo "Deleted Cookies" ?>
</body>

</html>
PHP Sessions
An alternative way to make data accessible
across the various pages of an entire website is
to use a PHP Session. A session creates a file in a
temporary directory on the server where
registered session variables and their values are
stored. This data will be available to all pages on
the site during that visit.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Sessions
Starting a PHP Session. A PHP session is easily
started by making a call to
the session_start() function.This function first
checks if a session is already started and if none
is started then it starts one. It is recommended to
put the call to session_start() at the beginning
of the page.

NEUST.SIC. Web Systems and Technologies 2. 2023


PHP Sessions
Session variables are stored in associative array
called $_SESSION[]. These variables can be
accessed during lifetime of a session.

Make use of isset() function to check if session


variable is already set or not.

NEUST.SIC. Web Systems and Technologies 2. 2023


<?php
session_start();

if( isset( $_SESSION['counter'] ) ) {


$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}

$msg = "You have visited this page ".


$_SESSION['counter'];
$msg .= "in this session.";
?>
PHP Sessions
Destroying a PHP Session. A PHP session can be
destroyed by session_destroy() function. This
function does not need any argument and a
single call can destroy all the session variables. To
destroy a single session variable,
use unset() function to unset a session variable.

<?php
unset($_SESSION['counter']);
?>
NEUST.SIC. Web Systems and Technologies 2. 2023

You might also like