PHPMaterial
PHPMaterial
Q: Explain how PHP is different with Java Servlets and Java Server Pages (JSP)
Ans:
Introduction:
Servlets and JSP both related to Java. They are used in developing Java based web
programming.
Servlets:
Servlet is a Java based server-side web technology. Servlets are used at server side. Servlets
can receive requests from clients and return responses. When client system requests a webpage,
HTTP request is sent to appropriate web server. Servlet that is running on a web server, receives
the request and generates the response based on the request.
Problems with Servlets:
In many Java servlet-based applications, processing the request and generating the
response are both handled by a single servlet class.
The web applications developed using servlet-based technology requires more time to
debug and enhance the application.
Java Server Pages(JSP):
JSP is a technology for developing web pages that include dynamic content. JSP contains
special elements apart from HTML elements. JSP elements are used to insert the dynamic content
in the page.
Problems with JSP:
JSP pages must be compiled on the server when first accessed and produces a noticeable
delay when accessing the JSP page for the first time.
JSP requires more disk space as both JSP page and resultant bytecode is stored at server
side.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 1
Q.What is the structure of a PHP Scriptlet? How to embed the script in HTML?
Ans:
PHP is an embedded scripting language when used in web pages. This means that PHP code
is embedded in HTML code. You use HTML tags to enclose the PHP language that you embed in
your HTML file. You create and edit web pages containing PHP the same way that you create and
edit regular HTML pages.
The PHP language statements are enclosed in PHP tags with the following form:
Structure of PHP Scriptlet
<?php
PHP processes all the statements between these two PHP tags. After the PHP section is
processed, it is discarded. If the PHP statements produce output, the PHP section is replaced by the
output. The browser doesn’t see the<< PHP section,
PHP Codethe browser
Here >> sees only its output, if there is any.
Example:
<Html>
<?php
echo "Welcome to PHP";
?>
<Body>
<br> This is our first Web Page
</Body>
</Html>
Q.What is Variable? Explain how to declare variables in PHP
Scripts Ans:
A Variable is an identifier that is associated with a particular memory location in the
computer's memory. A variable is capable of storing data values of type to which it is declared like
number, string, object, array or boolean. The value of a variable will be changed frequently during
its life in the program.
Variables are fundamental to programming. Values are given to the variables when the
script is run.
Declaring Variables:
A variable consists of a name preceded by a dollar sign($). Variable names can include
alphabets, numbers and underscore characters but they cannot include whitespaces. Each variable
name must begin with an alphabet or an underscore character.
Syntax:
$<Name of the variable>;
Example:
$a; $sno; $std_name $_found;
Initializing Variables:
We can assign a variable with some value at the time of its declaration using an assignment
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 2
statement.
Syntax:
$<Name of the Variable> = <Value>;
Example:
$std_name="Hema Gopika"; $found=true;
Sample Code:
Scope of <Html>
Variables:
<?php
The area of $a;the program where the variable is accessible is called "Scope" of the variable.
The scope of a variable defines the life span of that variable. A variable may have any one of the
$sno=123;
scopes like local, global or super global.
$std_name="Hema Gopika";
Local Scope: $found=true;
$a=10;
The variable that is declared inside a script will have the scope of entire script. If the
echo "Value
variable is declared inside of A:". then it will have a function scope.
a function,
$a; echo "<br>";
echo ScriptA.php
<Html>
$std_name; ScriptB.php
<Html>
?> <?php <?php
<Body> $a=10; $a=10;
</Body> echo echo
$a; $a;
</Html> ?> ?>
<Body> <Body>
</Body>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 3
In the above example, the variable ‘a’ of ScriptA is different from the variable ‘a’ of ScriptB.
Global Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
<Html>
outside a function.
<?php
global Keyword:function test() {
$x = 45;
The global keyword is used to access a global variable from within a function. To do this,
echo "Variable x inside function is:
use the global keyword before the $x";variables (inside the function):
} <Html>
Super Global Scope:
test(); <?php
Several predefined variables in PHP are "superglobals", which means that they are always
?> $x = 5;
accessible, regardless of scope - and you can access them from any function, class or file without
<Body> special. $y = 10;
having to do anything
function
</Body>variables are:
The PHP superglobal
myTest() { global
$GLOBALS $_SESSION
$_SERVER
$x, $y;
$_REQUEST $y = $x + $y;
Example: }
$_ENV $_POST myTest(
$_COOKIE $_GET ); echo
$_FILES $y;
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 4
$GLOBALS is a PHP super global variable which is used to access global variables
from anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Q.What is<Html>
datatype? Explain different datatypes supported by PHP ?
Ans: <?php
Data Type: $x = 55;
The type of
$ydata,
= 25; the programmer is going to store in a variable is called the "Data Type" of
a variable. The programmer can choose
function addition() { one data type for a variable depends on his requirement in
the program. Data type specifies the
$GLOBALS['z'] size and type
= $GLOBALS['x'] of values that can be stored in a variable.
+ $GLOBALS['y'];
PHP is a Loosely
}
Typed language, that is we need not specify the datatype to declare a
variable. It automatically
addition( determines the datatype to a variable at the time some data is assigned
to that variable. );Inecho
PHP, variables can be used flexibly that is the same variable can be used
for $z;
holding different
?> types of data values.
<Html>
<Body>
<?php
</Body> $x = 1234;
echo $x;
$x = "Laasya
Vemula"; echo $x;
$x = 78.5;
echo "$x";
$x=true;
echo "$x";
?>
<Body>
</Body>
</Html>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 5
Example:
Standard Datatypes:
Data Type Description Example
Integer Whole Number 25
Float or Double Floating-point Values 78.45
String Collection of characters “Hello”
Boolean Special values true or false True
Object
Array
Resource
NULL
Type Casting:
The process of converting data from one type to another is called "Type Casting". In this
process data of one type is converted into another possible and relevant type. We often do this
process when we need to store a value of one type into a variable of another type. We must cast
the value to be stored by preceding it with the type name in parentheses.
Syntax:
<Variable Name > = (Data Type) < Variable Name>;
Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 6
Example:
<Html>
Q. What is an operator?
<?php Explain various operators available in PHP?
Ans: $n=100;
An operatorecho
is a symbol
"IntegerorType:".is_integer($n);
series of symbols used to manipulate data stored in variables to
make it possible to$n=32.54;
use one or more values to produce a new value. A value operated on by an
operator is referredecho
to as"<br>Float
an operand. PHP supports a rich set of operators.
Type:".is_float($n);
Assignment Operator:$n="Hello";
Assignment echo
Operator is usedType:".is_string($n);
"<br>String to assign a value to a variable. The operator = is used as
assignment operator
?> in PHP. It takes two operands left operand and right operand. It assigns the
value of right operand to left operand.
Syntax : <Body> = Operand2;
Operand1
Example : </Body>
$n=100; $c=$a+$b;
</Html>
Arithmetic Operators:
Arithmetic Operators are used to construct mathematical expressions. Using these
operators, the programmer can build the statements to be performed arithmetic operations like
addition, subtraction, multiplication and division. These operators can be operated on numerical
data but not on boolean type data.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 7
Example:
Concatenation Operator:
<Html>
The concatenation
<?phpoperator is represented by a single period/dot (.) symbol. It treats
both the operands as strings. It appends the right operand to the left operand.
$a=15;
Syntax : Operand1.Operand2;
$b=6;
$res = $a+
Example : $b; echo
"Hello". "World" Result : HelloWorld
$res; echo
"<br>";
Increment and Decrement Operators:
$res = $a-
PHP supports two$b; operators
echo
Increment and Decrement operators which are used to
increase or decrease the$res;value
echo
of a variable by one. Both these operators take only one
operand, so they are called as
"<br>";Unary operators.
$res = Operator Meaning
$a*$b; ++ Increment
echo $res;
-- Decrement
echo
"<br>"; operators can be used in two different forms:
Both Increment and Decrement
$res =
Pre-Increment and Post-Increment Pre-Decrement and Post-Decrement
$a/$b;
Post-Increment / Post-Decrement:
echo $res;
In this form of operation,
echo
the expression is evaluated after all other actions have been
completed. "<br>";
Syntax : <Operand>++;
$res = $a%
<Operand>-
-; Ex : $a - -;
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 8
Pre-Increment / Pre-Decrement:
In this form of operation, the expression is evaluated first prior to all other actions.
Syntax : ++<Operand>;
--
<Operand>; Ex : ++$a;
Example: <Html>
<?php
$a=10; echo $a;
$b=$a++;
echo "<br>$a"; echo "<br>$b";
$b=++$a;
echo "<br>$a"; echo "<br>$b";
$b=$a--;
echo "<br>$a"; echo "<br>$b";
$b=--$a;
echo "<br>$a"; echo "<br>$b";
?>
<Body>
</Body>
</Html>
Comparison Operators:
Comparison operators perform comparative tests using their operands and return the
Boolean value true if the test is successful or false if the test fails. These operators are useful
when we need to compare two quantities of values with each other.
Syntax : Operand1 Operator Operand2;
Operator Meaning
== Equal To
!= Not Equal To
=== Identical
> Greater Than
Greater Than or Equal
>= To
< Less Than
<= Less Than or Equal To
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 9
Example :
<Html>
<?php
$a=10;
$b=7;
$res =
$a>$b;
echo $res;
$res =
$a<$b;
echo $res;
$res =
$a>=$b;
echo $res;
$res =
$a<=$b;
echo $res;
$res =
$a==$b;
echo $res;
$res = $a!
=$b; echo
$res;
$res =
$a=="10";
echo $res;
$res =
$a===10;
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 10
Logical Operators:
Logical Operators test combinations of Boolean values and return a Boolean value as result.
The expression which is formed as combination of two or more comparison expressions is called
Logical Expression.
Syntax : <Comparison Expression1> Operator <Comparison Expression1>;
Operator Meaning
|| Or
or Or
xor Exclusive Or
&& And
and And
! Not
Example :
<Html>
<?php
$a=10;
$b=7;
$c=12;
$res =
($a>$b)&&($b<$c);
echo $res;
$res =
($a>$b)and($b<$c);
echo $res;
$res = ($a<$b)||
($b<$c); echo $res;
$res =
($a<$b)or($b<$c);
echo $res;
$res = ($a>$b xor
$b<$c); echo $res;
$res = !
($a<$b); echo
$res;
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 11
Q.Explain about Constants in PHP?
Ans:
A Constant is a fixed value whose value cannot be changed during its life in the program.
Constants are used when the programmer wants work with a value that must remain unchanged
throughout the script. In PHP, we can define constants using the built-in function : define().
Syntax : define(Name of the constant, Value);
Example :
<Html>
Q.Explain various Switching
<?php Flow statements available in PHP with suitable examples ?
Ans: define("PI",3.14);
$area
In normal cases, the =
statements placed inside a script are executed in the order in which
2.5*3.2*PI; echo
they are placed. This type of execution is called Sequential Execution. These kinds of programs
$area;
produce same results every time we run the script. These web pages are called as static web
?>
pages.
<Body>
To make our </Body>
web pages dynamic, we add switching flow statements to our script code.
When a program breaks the sequential flow, and jumps to another part of the code, it is called
Branching.
PHP supports several structures for constructing the statements to switch the flow of
execution. These statements are called "Decision Making" statements. Decision making statements
are used to execute or skip a set of statements basing on a condition.
There are the following kinds of decision making structures available in PHP:
1. if Statement
2. switch Statement
3. Conditional Operator Statement
if Statement:
The most frequently used decision-making structure by the programmers is ‘if' statement. if
statement is used to control the flow of execution of statements in a program. In PHP, if statement
can be used in the following forms:
a) Simple if Statement
b) if..else Statement
c) if..elseif ladder
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 12
Simple if Statement :
Simple if statement is used to execute one set of statements based on the results of a given
test expression. If the given test expression evaluates to true, then statement block is executed,
otherwise the statement block is skipped.
Syntax: if(Expression) {
Statement
Block
}
Example:
<?php
if..else Statement:
$n=5;
The if..else statement is used to execute one set of statements among two mutually
if($n>0
exclusive set of )statements.
{ Therefore at any time, only one block of statements will be
executed. Syntax: if(Expression) {
echo "N is Positive Integer";
}Statement Block 1
} else {
Statement Block 2
}
Example:
<?php
$n=-5;
if($n>0
){
echo "N is Positive Integer";
} else {
echo "N is Negative Integer";
}
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 13
if..elseif Statement:
The if..elseif statement is used when we compare more than one condition to execute
one set of statements among several mutually exclusive statements.
Syntax: if(Expression 1) { Example:
switch Statement:
The switch statement is an alternative way of changing flow based on the evaluation of
an expression. It is a multi-way decision making statement which can be used as alternative for
if..elseif statement.
Syntax: switch(Expression) { Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 14
Conditional Operator ( ? : ) :
PHP supports special operator called Conditional Operator or Ternary Operator which
can be used alternatively to if..else statement. It returns a value derived from one of two
expressions. Syntax: (expression) ? val1 : Val2;
Example:
<?php
$a=10;
$b=20;
$big = ($a>$b)?$a:$b;
echo "Biggest Value:
Q. Explain various Looping Control statements available in PHP with suitable examples
Ans:
Scripts can also decide how many times to execute a block of code. Looping Control
Statements are designed to perform repetitive tasks because they continue to operate until a
specified condition is achieved or explicitly we choose to exit the loop.
PHP supports the following looping control statements.
The while Statement:
A while statement executes a block of code for as long as the expression evaluates to true
repeatedly. Each execution of a code block within a loop is called an iteration.
Syntax: while (Expression)
{ Loop
Body
}
The loop body is allowed to be executed only when the given condition evaluates to true.
As long as the condition evaluates to true, it allows the loop body for execution repeatedly. Once
the loop body got executed, it again checks the condition if it evaluates to true it allows the loop
body to execute once again. This process will be continued until the given condition becomes false.
Example:
<?php
$i=1;
while($i<=10)
{
echo "$i<br>";
$i++;
}
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 15
The do..while Statement:
The do..while loop is almost similar to while statement but it is an exit-controlled loop
statement as it allows the loop body to be executed for the first time without any condition.
Syntax: do {
Loop Body
} while(Expression);
<?php
$i=
1;
do
{
echo "$i<br>";
$i++;
The for Statement:
The for loop is the most convenient construct among all the looping structures of PHP.
It is an entry-controlled loop, which tests the condition prior to execute the body part from the
first iteration onwards.
Syntax: for(initialization expression; test expression; modification expression)
{ Loop Body
}
Initialization Expression is used to initialize all the sentinel variables which are to be
used in the loop.
Test Expression part contains the actual conditional expression which controls the
execution of the loop.
Modification Expression is used to place increment or decrement expressions of the
variables.
Example:
<?php
for($i=1;$i<=10;$i+
+) echo
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 16
Q. Explain break and continue statements with suitable examples
Ans:
Looping statements are used to execute a set of statements repeatedly for a finite
number of times. The number of times a loop is repeated is decided in advance and the test
condition is written to achieve this.
When the programmer wants to skip some portion of the loop body, they can use
jumping statements. Jumping statements are used to transfer the control from one part of the
code to another part of the code.
PHP supports the following statements as jumping statements which can be used to
control the flow of the control:
1. break
2. continue
break statement:
Example:
<?php
$n=0;
$i=1;
$res;
while($i<=10)
{
if($n==0) {
echo "Dividing Zero results
Zero"; break;
}
$res=$n/$i;
echo "$res<br>";
$i++;
}
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 17
continue statement :
In PHP, continue statement is used to skip the execution of some portion of the code
for a while in a loop and continues the execution of the loop. Whenever the continue
statement is encountered inside a loop it skips the execution of the statements that are
followed it and continues the execution of the loop further. Unlike break statement, continue
statement does not terminate the loop.
Syntax : continue;
Example:
<?php
Q. What is Function? What are the advantages of using functions in programs?
$i=0;
Ans:
while($i<10)
A function is a piece of code in a larger program. The function performs a specific task. A
{
function accepts values, processes the values and then perform an action like printing data to
$i++;
the browser then returns a new value sometimes.
if($i>=5&&$i<=
A function is a self-contained block of code that can be called by the script for multiple
7)
times. When a function is called, the function’s code is executed and performs a specific task. We
continue;
can pass values called parameters to a function while it is being called.
echo
The advantages of using functions are:
Reducing duplication of code
Decomposing complex problems into simpler pieces
Improving clarity of the code
Reuse of code
Information hiding
Explain how to define a function and how to call a function in PHP?
Ans:
Defining a function is nothing but providing function body or function code. If the
programmer defines a function, then it is called User-Defined Function. We can define our own
functions using the keyword function.
Syntax: function <Name of the function> (List of Parameters) {
Function Code
}
The name of the function follows the keyword function and precedes a pair of
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 18
parenthesis. Functions can be defined with or without parameters.
Example:
<?php
function welcome( ) {
echo "<h1>Welcome to PHP Functions"; Function Declarator
}
?>
If the function requires any parameters, they must be declared by separating by comma
symbols within the parenthesis. These parameters are filled by the values what we use to call that
function.
Example:
<?php
Parameter
function add($a, $b) {
$res = $a+$b;
?>
Default Parameters:
We can also define a function with the parameters whose values are assigned to some
default values. If we do not provide any value to those parameters, the default values are used in
the function code.
Example: <?php
Default Parameter
function today($day, $month, $year=2017) {
Calling Functions:
Defining a function does nothing unless we invoke the function by placing a proper call to
that function in the script. We call a function by using its name and zero or more parameters.
While calling the function, we pass appropriate arguments to the function. The number of
parameters placed in the function declarator must be matched with the number of arguments
placed in the function call.
Example: <?php
function welcome( ) {
} Function Call
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
In the above example, we defined a function welcome( ) with zero parameters. While
calling this function we need not pass any parameter since it accepts no parameters.
Example:
<?php
In the above example, we defined a function today( ), with three parameters. Among those
three parameters, one parameter ‘year’ is default parameter. If we do not provide any argument to
the default parameter, it takes the default value supplied in the function declarator. Passing an
argument by Value:
When we pass arguments to functions, they are stored as copies in parameter values. Any
changes made to these local copies in the body of the function are local to that function and are
not reflected beyond it.
Example:
<?php
function lifeSpan($formal) {
echo "<br>Formal:
$formal";
$formal=$formal+50;
echo "<br>Formal: $formal";
}
$actual=200;
echo "<br>Actual:
$actual";
lifeSpan($actual);
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Passing an argument by Reference:
function lifeSpan(&$formal) {
echo "<br>Formal: $formal";
$formal=$formal+50;
echo "<br>Formal: $formal";
}
$actual=200;
echo "<br>Actual: $actual"; lifeSpan($actual);
echo "<br>Actual: $actual";
?>
Calling a function from another function:
We can also call a user-defined function from another user-defined function.
Example:
<?php
function one( ) {
echo "<h1> I am function one";
}
function two( )
{ one( );
}
two( );
?>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<?php
Calling Function
function findBig($a, $b) {
return ($a>$b)?$a:$b;
Called Function
}
<?php
function variableScope( ) {
$x=100;
}
echo $x;
?>
The above code generates an error in printing the value of variable ‘x’ since it is not
available outside the function variableScope(). The life span of the variable ‘x’ is only inside the
function variableScope(). It can not be accessed outside the function.
Accessing Variables with global statement:
Normally, the variables declared outside a function are not accessible inside that
function. That is, a function can access only the variable that are declared inside that function
and those variables are called local variables. Apart from local variables, a function can access
the variables that are declared outside a function using the keyword global.
Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<?php
<?php
$x=100;
$x;
function variableScope( )
function variableScope( ) {
{ global $x;
$x=100;
$x=200;
}
echo $x;
variableScope(
}
); echo $x;
variableScope();
?>
?>
Error No Error
function lifeSpan( ) {
$count=0;
$count++;
echo "<br>Count: $count";
}
lifeSpan(
);
lifeSpan(
Sometimes the programmer may want the value of a local variable what was in its
previous execution. In this case, automatic local variables are not useful because they lose the
value everytime they die and starts a fresh life.
For this, we use static variables. If we declare a variable as static, the variable remains
local to the function, and the function remembers the value of the static variable from
execution to execution.
Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<?php
function lifeSpan( )
{ static
$count=0;
$count++;
echo "<br>Count: $count";
}
lifeSpan(
);
lifeSpan(
$colors =
array("Red","Green","Blue","Orange","Pink"); echo
$colors[0];
2)
<?php <?php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Both the above scriptlets creates an array colors with 5 elements with starting index 0
and ending index 4.
Adding more elements to the array:
We can add elements to an existing array by using array operator [ ]. Once we create
an array by using either array() function or array operator, we can add more elements to the
array one element at a time.
Example:
<?php
$colors = array("Red","Green","Blue","Orange","Pink");
$colors[ ] =
"Yellow"; echo
$colors[5];
We can add more elements to the associative array by specifying key and its value.
Example:
<?php
<?php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Creating Multi-Dimensional Arrays:
A multi-dimensional array is an array of arrays. Here each element is again an array with
some elements.
Example:
<?php
$fruits = array(
array("name"=>"Apple", "color"=>"Red"),
array("name"=>"Banana",
"color"=>"Green"),
array("name"=>"Grapes",
"color"=>"Black"), array("name"=>"Sapota",
"color"=>"Brown")
);
Q. Explain various Constructs and Functions related to Arrays
Ans:
PHP supports several built-in functions which help us to work with arrays more effectively.
Some of the most commonly used built-in functions are explained in the following section.
count( ) / sizeof( ):
Both these functions count and return the number of elements in an array.
Example:
<?php
$fruits =
array("Apple","Banana","Sapota","Grapes","Oranges"); list($k,
$v)=each($fruits);
echo "$k--$v";
foreach( ):
This function is used to retrieve the elements of an array element by element starting
from the very first element and moving towards the end of the list.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<?php
$fruits =
array("Apple","Banana","Sapota","Grapes","Oranges");
foreach($fruits as $f=>$fv) {
echo "<h1>Key=".$f." Value=".$fv;
}
array_push( ):
This function adds one or more elements to the end of an existing array.
Example:
<?php
$fruits = array("Apple","Banana","Sapota","Grapes","Oranges");
echo "<h2>No.of Elements:".count($fruits);
array_push($fruits,"Pineapple");
echo "<h2>No.of Elements:".count($fruits);
?>
array_pop( ):
This function removes and returns the last element of an existing array.
Example:
<?php
$fruits =
array("Apple","Banana","Sapota","Grapes","Oranges"); echo
"<h2>No.of Elements:".count($fruits);
echo "<h2>Popped Element:".array_pop($fruits);
echo "<h2>No.of Elements:".count($fruits);
array_unshift():
This function adds one or more elements to the beginning of an existing array.
Example:
<?php
$fruits =
array("Apple","Banana","Sapota","Grapes","Oranges"); echo
"<h2>First Element:".$fruits[0];
echo "Count:".count($fruits);
array_unshift($fruits,"Cherry");
echo "<h2>First Element:".
$fruits[0]; echo
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
array_shift():
This function removes and returns the first element of an existing array.
Example:
<?php
$fruits = array("Apple","Banana","Sapota","Grapes","Oranges");
echo "<h2>First Element:".$fruits[0];
echo "<h2>Count:".count($fruits);
$felement = array_shift($fruits);
echo "<h2>First Element:".
$felement; echo
"<h2>Count:".count($fruits);
array_merge( ):
This function returns an array containing all the values within a given array.
Example:
<?php
$student = array("sid"=>"12345", "sname"=>"Anil Kumar","course"=>"B.Sc");
$values =
array_values($student); echo
$values[1];
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Q.Explain how Strings are formatted in PHP
Ans:
PHP provides many functions with which we can format and manipulate strings. Most
of the content in the web is in String format, so we need to manipulate those values in
majority cases. PHP provides number of powerful functions to manipulate the Strings very
easily.
Formatting Strings:
PHP provides the following two functions to apply formatting while displaying the
results. Formatting may include rounding numbers to a given no.of decimal places, define the
number system etc.
1. printf( ) 2. sprint( )
printf( ):
The printf() function requires a string argument known as format control string and
some additional arguments. The format control string contains instructions regarding the
display of additional arguments.
Example:
<?php
printf("<h2>Value: %d", 55.36);
?>
The above example displays the given value 55.36 as 55 since we used the format
control string %d which converts a given value into an integer while displaying it.
The format control string is also called as conversion specification. A conversion
specification begins with a percent(%) symbol. We can include multiple conversion
specifications as we need in the code. The number of conversion specifications must be equal
to the number of additional arguments we pass to printf() function.
Specifier Description
%d Display argument as Decimal Number
%b Display an integer as Binary Number
%c Display an integer as ASCII Value
%f Display an integer as Floating-Point Number
%o Display an integer as Octal Number
%s Display argument as a String
%x Display an integer as a hexadecimal number
Example:
<?php
<?php
$n=123;
printf("<h2>Decimal: %d",
$n); printf("<h2>Binary: %b",
$n); printf("<h2>Double: %f",
$n); printf("<h2>Octal: %o",
$n); printf("<h2>String: %s",
$n);
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Padding Output with a Padding Specifier:
Padding specifier is used to add leading characters followed by the output. Sometimes we
may need to pad output with some characters, in that case padding specifier is used. The padding
specifier should directly follow the percent sign that begins a conversion specification.
Example:
<?php
$n=35;
printf("<h2>Decimal: %04d", $n);
?>
The above example will produce the output 0035 since the variable contains a number with
two digits and we are displaying the number in 4-digit width. The remaining two positions are
padded with zeros.
Example:
<?php
echo "<pre>";
$n="Hello";
printf("<h2>String: % 10s",
$n); echo "</pre>";
?>
The above example will produce the output Hello by padding 5 white spaces before the
value since the variable contains 5 characters and we are displaying the value in 10 characters
width.
Specifying a Field Width:
We can specify the number of spaces within which our output should fit. A field width
specifier is an integer that should be placed after the percent sign that begins a conversion
specification.
Example:
<?php
echo "<pre>";
printf("%20s\n",
"Hello");
printf("%20s\n", "Hai");
printf("%20s\n", "How Are
You?"); printf("%20s\n", "Well");
printf("%20s\n",
"Good"); echo "</pre>";
Specifying Precision:
While displaying floating-point format data, we can specify the precision to which we want
to round your data. For this, we use a precision specifier which should be placed before the type
specifier. It consists a dot(.) followed by the number of decimal places we want to round.
Example:
<?php
printf("%.2f",78.95497);
?>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<?php
$products = array("Cinthol"=>"36.564", "Liril"=>"34.2154","Lux"=>"33.4568");
echo "<pre>";
printf("%-20s%20s\n","Product Name","Price"); printf("%'*40s\
n","");
foreach($products as $key=>$val)
printf("%-20s%20s\n",$key,
$val);
echo "</pre>";
?>
We can use this function to determine the length of a string. This function requires a string as its
argument and returns an integer representing the number of characters in the given string. Example:
<?php
$msg = "Hello World";
echo "Length: ".strlen($msg);
?>
strstr( ):
We can use this function to test whether a string exists within another string. This function requires
two string arguments source and find strings. This function returns the portion of the source string
beginning with the find string if it exists, otherwise returns false.
Example:
<?php
$msg = "Hello World, welcome to PHP";
$res =
strstr($msg,"World");
echo $res;
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
strpos( ):
We can use this function to check whether a string exists and to find the position of the string within
another string.
Example:
<?php
$msg = "Hello World, welcome to PHP";
$res =
strpos($msg,"World");
echo $res;
substr( ):
We can use this function to extract a sub-string of a string from a given index position(start)
and by specifying the number of characters . It requires three arguments one string and two integer
type values.
Example:
<?php
We can parse a string word by word by using strtok() function. This function requires two arguments. First
argument is the string which we want to split, the second is the delimiter based on which we split the first
argument into tokens.
When the function is called for the first time, returns the first token and the source string is cached. For
subsequent calls, we should pass only the delimiter. The function will return the next found token for every call
and return false if no token is found.
Example:
<?php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
UNIT – II
class Student {
public $sid=12345;
public $sname = "Anil
Kumar"; public $gender =
'M';
In the above example, the class Student contains three properties sid, sname and gender.
Accessing the Properties of a class:
We can access the properties of a class outside the class with the help of an object’s
reference variable. To create an object, we use the keyword ‘new’ which instantiates the class.
Syntax: $<Object Name> = new <Class Name> ( );
$<Object Name> -> <Member Variable Name>;
Example:
<?php
class Student {
public $sid=12345;
public $sname = "Anil Kumar"; public $gender = 'M';
}
$s = new Student( ); echo "<H2>$s->sid"; echo "<H2>$s->sname"; echo "<H2>$s->gender";
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Defining Methods in a class:
Each class contains a set of one or more methods to manipulate the data values that are
stored in the properties. Methods add functionality to the objects.
Syntax: function <Name of the Function>(Parameter List) {
Function Body
}
Example:
<?php
class Student {
function showData( ) {
echo "<h2>12345";
echo "<h2>Anil
Kumar"; echo
"<h2>M";
}
class Student {
function showData( ) {
echo "<h2>12345";
echo "<h2>Anil
Kumar"; echo
"<h2>M";
}
}
$s = new Student( );
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<?php
class Student {
public $sid=12345;
public $sname = "Anil
Kumar"; public $gender =
'M';
function showData( ) {
echo "<h2>Student ID: ".$this->sid;
echo "<h2>Student Name: ".$this->sname;
echo "<h2>Student Gender: ".$this-
>gender;
}
}
class College {
public
$name="E.S.S.D.C";
function showData( ) {
echo "<h2>College: ".$this->name;
$this->name="E.S.S.D.C&P.G.C";
echo "<h2>College: ".$this-
>name;
}
}
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
2. Explain how to create instances using
Constructors Ans:
To create a new instance of a class also called object, we can use the new operator in
conjunction with the class name. Here, a special function called Constructor is used to create
the object. The class constructor serves to initialize the instance.
Syntax: <Reference Variable Name> = new <Class Name along with Constructor>;
Example:
<?php
$this->dept = $c;
ConsTRUCTors.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<?php
$this->dept = "YYYYYY";
<?php
class Employee
{ public $eid;
public
$ename;
public $dept;
function construct($a=12345, $b="Mahesh Babu", $c="Sales" ) {
$this->eid = $a;
$this->ename = $b;
$this->dept = $c;
}
function showValues() {
echo "<h2>$this-
>eid";
echo "<h2>$this-
>ename"; echo
"<h2>$this->dept";
}
}
$e = new Employee();
$e->showValues();
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
3. Explain how to Control Access to Class Members using Visibility controls
Ans:
Sometimes it is necessary to restrict the access to some variables and methods from
outside the class. In PHP, we achieve this by applying visibility modifiers to the instance
variables and methods. These visibility modifiers are also called as 'Access Modifiers'. An access
specifier is a keyword that represents how to access the members of a class.
PHP supports three different types of visibility modifiers: public, protected, and private.
All these modifiers provide different level of protection.
public:
The property or method declared as public can be accessed by any other code. This is
the default visibility for all class members in PHP.
Example:
<?php <?php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
private:
The property or method declared as private can be accessed only within the same class.
Attempting to access these members from outside the class raises an error.
Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
protected:
The property or method declared as protected may be accessed within the same class
and from any class that extends that class. Attempting to access these members from outside
the class raises an error.
Example:
<?php
class Person {
protected
$name;
protected $age;
}
class Student extends Person
{ private $sid;
private $course;
public function setValues( ) {
$this->name = "Harish";
$this->age = 22;
$this->sid = 12345;
$this->course = "M.Sc(CS)";
}
public function showValues( )
{ echo "<h1>$this->sid";
echo "<h1>$this->name";
echo "<h1>$this-
>course"; echo
"<h1>$this->age";
}
}
$s = new Student();
$s->setValues();
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
4. Explain Inheritance through extending
classes Ans:
Inheritance means acquiring the qualities of one class to another class. These qualities
include both properties and methods of a class. We can create a new class by extending the
features of an existing class. This mechanism of creating new classes based on existing classes
gives the advantage of reusability of the code.
Syntax: class <Name of the NEW class> extends <Name of the OLD class> {
Class Definition
}
Example:
<?php
class Person {
public $name;
public $age;
public
$gender;
}
class Student extends Person
{ function setData( ) {
$this->name = "Anil Kumar";
$this->age = 20;
$this->gender = 'M';
}
function showData( ) {
echo "<h3>Student Name: ".$this-
>name; echo "<h3>Student Age: ".$this-
>age;
echo "<h3>Student Gender: ".$this->gender;
}
}
$obj = new Student();
Method Overriding:
Method Overriding is the concept of defining a method in both Parent class and its child
class by following the same signature. Here the method that is defined in the Child class
overrides the method in the Parent class.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<?php
class Animal {
function walk( ) {
echo "<h2>All animals can walk";
}
}
class Horse extends Animal { function walk( ) {
echo "<h2>Horse runs very fast";
}
}
$a = new Animal();
$a->walk();
$h = new Horse();
$h->walk();
?>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
5. Explain about Abstract Classes and
Methods Ans:
An abstract method is one that is declared by name only, but it contains no body. The
implementation is left to the derived class. By using abstract method mechanism, we make a
method of a class must always be redefined in its subclasses. It makes method overriding
compulsory by all the sub classes of a class.
While working with abstract methods, the following facts should be remembered.
1. Any class that contains one or more abstract methods must itself be declared as abstract.
2. An abstract class cannot be instantiated, we must extend it in another class and then
create instances of the derived class.
3. A class that extends the abstract class must implement the abstract methods of the
parent class, otherwise it should be declared as abstract.
Syntax: abstract pUblic fUnction <Name of the abstract method>;
abstract class <Name of the abstract class>
Example:
<?php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
6. Explain about
Interfaces Ans:
An Interface is a collection of abstract methods and constants. Interface defines only
abstract methods and final fields. It cannot have any concrete methods in it. It tells the classes
which implement the interface to do something without how to do it.
Syntax: interface <Name of the Interface> {
Method declarations
}
Implementing the interface:
Once an interface is declared, we can implement it by using a class and we can
instantiate it to give life to it.
Syntax: class <Name of the class> implements <Name of the Interface> {
Method Definitions
}
We can also implement more than one interface at a time using single class.
Syntax: class <Name of the class> implements <Name of the Interfaces separated by , > {
Method Definitions
}
Example:
<?php
interface Animal {
public function
walk(); public
function eat(); public
function speak();
}
class Lion implements Animal
{ public function walk( ) {
echo "<h1>Lion walks like a king";
}
public function eat( ) {
echo "<h1>Lion eats flesh";
}
public function speak( ) {
echo "<h1>Lion
roars";
}
}
$l = new Lion();
$l->walk();
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
7. Explain Class
Destructors Ans:
Classes can have both constructors and destructors. A destructor is simply a method
that is invoked when an instance of the class is removed from the memory. Destructor methods
are used to destroy the object created by the constructor methods.
Example:
<?php
class Student {
function construct() {
echo "<h1>Object is Created";
}
function test() {
echo "<h1>I am a Function";
}
function destruct() {
echo "<h1>Object is Destroyed";
}
}
$s = new Student();
$s->test();
?>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
UNIT - III
Ans: <Head>
Cookies are files that get written to a temporary file on a user’s computer by a web
<?phpstore information that can be read by the online application for
application. Cookies
authenticating a user as unique. By identifying the users uniquely, web application can serve
setcookie("ck_user", "munirathnam", time()+60);
individual users without any confusion.
The problem withsetcookie("ck_pwd", "teacher",
cookies is that they time()+60);
are insecure because they are stored on user’s
computer. Because of this some users turn off them in their browser security settings. But if we
?>
use cookies, they help a lot in developing a good web application.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Reading Cookies:
Once the cookie is set with a value, we can read its value until its expiration. After
reading the value of a cookie it can be used in our application like any other variable. We can
not read the value of a cookie, once it gets expired.
Example:
<Html>
<
if(isset($_COOKIE["ck_user"]))
$uname = $_COOKIE["ck_user"];
else
$uname = ""; if(isset($_COOKIE["ck_pwd"]))
$password = $_COOKIE["ck_pwd"];
else
$password = "";
ReadCookie.php
Ans:
Cookies are files that get written to a temporary file on a user’s computer by a web
application. Cookies store information that can be read by the online application for
authenticating a user as unique. By identifying the users uniquely, web application can serve
individual users without any confusion.
The problem with cookies is that they are insecure because they are stored on user’s
computer. Because of this some users turn off them in their browser security settings. But if we
use cookies, they help a lot in developing a good web application.
Deleting Cookies:
Once the cookie is set with a value, it remains live until the expiration time is over.
Cookies will disappear by themselves if we set expire time to them. If we do not set any time to
a cookie, it will die when the browser window is closed. We can also explicitly delete the cookie
by assigning a blank space using the method ‘setcookie()’.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
DeleteCookie.php
<Html>
4: What is a cookie?
<Head>How we write and use a cookie class?
Ans: <?php
setcookie
Cookies are files ("ck_user","",time
that get ()+60); file on a user’s computer by a web
written to a temporary
application. Cookies store information that can be read by the online application for
authenticating a user setcookie ("ck_pwed","",time
as unique. ()+60
By identifying the ); uniquely, web application can serve
users
individual users without
?> any confusion.
The problem with cookies is that they are insecure because they are stored on user’s
</Head>
computer. Because of this some users turn off them in their browser security settings. But if we
use cookies, they help a lot in developing a good web application.
Writing a Cookie Class:
To make it is easy to work with cookies, we can write our own classes which offer more
easy methods for creating, accessing, changing and deleting cookies. For this we develop a class
with various methods for controlling the functionality of the cookies.
Using a Cookie Class:
Once we create our own class, we can create an object to that class and use the
functionality of the cookies very easily.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<Html>
<Head>
<?php
What is HT<T/PHHtm class
elaMyCookie {
>der in PHP? How to redirect to a different location using
private
$cname;
headers Ans: private
$cvalue;
private $cexp;
HTTP Headers arepublic
powerful
functionsets of functionalities.
construct( ){ These headers are used to control
everything like setting the current page location, finding out what file format is being displayed
$args = func_get_args();
and managing all aspects of $this->cname
the browser = $args[0];
cache.
$this->cvalue = $args[1];
To work with HTTP Headers, we= use
$this->cexp the method called ‘header()’. The prototype of the
$args[2];
method is as follows: }
public function
voidsetmycookie( ){
header(string, bool, int)
setcookie($this->cname, $this->cvalue, $this->cexp);
Redirecting to a different} location:
One of the more public
common function readmycookie(
uses ){
of HTTP Headers is redirecting a script. By using headers
return $_COOKIE[$this-
inside processing scripts, we can force
>cname]; the browser to return to any page we want.
}
public function changemycookie($newval) {
$_COOKIE[$this->cname]=$newval;
}
public function deletemycookie( ) {
$_COOKIE[$this->cname]="";
}
}
$mc = new MyCookie("visitor","100",time()+60);
$mc->setmycookie( );
echo "<h1>Visitor ID:".$mc->readmycookie();
$mc->changemycookie("101");
echo "<h1>Visitor ID:".$mc->readmycookie();
$mc->deletemycookie();
echo "<h1>Visitor ID:".$mc->readmycookie();
?>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<Html>
<Body>
<Table>
<TR> <TD> User Name </TD> <TD> <Input Type='Text' name='username'> </TR>
<TR> <TD Colspan=2 Align='center'> <Input Type="Submit" Value="Go Next"> </TD> </TR>
</Table>
User.html
<?php
if(trim($_POST['username'])!=="")
else {
header("Location:
User.html"); exit;
HeaderTest.php
5. What is HTTP Header in PHP? How to send content type other than HTML using
headers Ans:
HTTP Headers are powerful sets of functionalities. These headers are used to control
everything like setting the current page location, finding out what file format is being displayed and
managing all aspects of the browser cache.
To work with HTTP Headers, we use the method called ‘header()’. The prototype of the
method is as follows:
void header(string, bool, int)
Sending content types other than HTML:
Sometimes we may want to use the header() function to output a type of file format that
may not be an actual webpage.
Example:
<Html>
<Head>
</Head>
<Body>
<div align='center'>
<img src="GenerateImage.php" alt="Nature">
</div>
</Body>
</Html>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Image.html
HeaderTest.php
<?php
6. What is HTTP$path = in PHP? How to use downloadable files?
Header
Ans: "Beach.jpeg";
if(is_file($path))
HTTP Headers are powerful sets
if($file=fopen($path, of{ functionalities.
'rb')) while(! These headers are used to control
everything like setting the current page location, finding out {what file format is being displayed and
feof($file)&&(connection_status()==0)
managing all aspects of $f the.=browser
fread($file,
cache.1024*8);
To work with } HTTP Headers, we use the method called ‘header()’. The prototype of the
method is as follows:fclose($file);
} header(string, bool, int);
void
header("Content-type:
Forcing ‘SaveAs’ image/jpeg");
Download: print $f;
Sometimes we may want to use the header() function to download a type of file format
that may not be an actual webpage.
Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Implementing Sessions:
Sessions are handled like cookies but with major difference. We create a session state using
the ‘session_start()’ function. Then we can use and access these session values using the
$_SESSION superglobal. Using $_SESSION, we can add, remove or modify session values. Before
using sessions, we must enable session state using session_start() function.
Example:
<Html>
<Head>
<?php
session_start();
$uname = "essdc";
SetSession.ph
p
$password = "college";
$_SESSION['user'] = $uname;
$_SESSION['pwd'] =
$password;
print_r($_SESSION);
unset($_SESSION['user']);
unset($_SESSION['pwd']);
print_r($_SESSION);
8. What is Session? Explain how they are used to store simple data types in
sessions Ans:
Cookies are less trusted because they are stored at client end. So, we need a way to
avoid storing of files at client end. For this we use Sessions which store on the actual Server
instead of client.
Storing Simple Datatypes in Sessions:
Sessions are used to store data of simple data types like integer, floating-point, string etc.
PHP Sessions handle these values very effectively.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<Html>
<Head>
<?php
session_start();
$_SESSION['sid'] = 12345;
$_SESSION['sname'] = "Anil Kumar";
$_SESSION['gpa'] = 8.2;
print_r($_SESSION);
unset($_SESSION);
?>
</
Head>
<Body>
</Body>
SimpleDatatypes.php
9.What is Session? Explain how they are used to store complex data types in sessions
Ans:
Cookies are less trusted because they are stored at client end. So, we need a way to avoid
storing of files at client end. For this we use Sessions which store on the actual Server instead of
client.
Storing Complex Datatypes in Sessions:
Sessions are used to store data of complex data types like classes using objects. Using
this technique, we can easily store large quantities of data within a single object.
Example:
<Html>
<Head>
<?php
class Student { public $sid; public $sname; public $gpa;
public function construct() {
$this->sid = 12345;
$this->sname = "Anil Kumar";
$this->gpa = 8.2;
}
}
session_start();
$_SESSION['std'] = new Student(); echo $_SESSION['std']->sid;
echo $_SESSION['std']->sname; echo $_SESSION['std']->gpa;
?>
</Head>
ComplexDatatypes.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
10. Explain how to authenticate users in communication over theweb
Ans:
Managing user authentication through Cookies and Sessions is more flexible. Using the
techniques called Cookies and Sessions, we can easily manage our authentication process.
Example:
<Html>
<Head>
<?php
$uname = "essdc";
$pwd = "college"; session_start();
$_SESSION['username'] = $_POST['un'];
$_SESSION['password'] = $_POST['pw'];
if(strcmp($_SESSION['username'],$uname)==0&&strcmp($_SESSION['password'],$pwd)==0)
echo "<h2>You are logged in";
else
echo "<h2>Login Failed"; unset($_SESSION['username']); unset($_SESSION['password']);
?>
</Head>
<Body>
UserAUthentication.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
11. Explain how to Read Environment and
Configuration variables Ans:
PHP provides a way to use and verify the configuration settings and
environment variables relative to the server space. By having access to environment
variables, we customize our scripts to work optimally on the platform that is available.
By having access to configuration variables, we can customize the PHP environment.
Using these variables we can use the details of the system like file locations,
computer name etc.
Example:
<Html>
<Head>
<?php
echo "<h2>".getenv('ProgramFiles');
echo
"<h2>".getenv('COMPUTERNAME');
?>
</
Head>
ReadEnvvariables.php
Q. Explain how to work with Date and Time functions in PHP Ans:
The date and time functions allow us to get the date and time from the server
where our PHP script runs. We can then use the date and time functions to format the
date and time in several ways.
Example:
<?php
$timestamp = getdate();
echo
"<h1>$timestamp[0]";
$today =
date('d/m/y'); echo
"<h1>$today";
$today = date('D-M-
Y'); echo
"<h1>$today";
$now =
date('h:i:s',time()); echo
DateandTime.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
UNIT-IV
Element Description
TEXT A simple text box
PASSWORD Text box that hides the input
HIDDEN Field that is not visible but contains data
SELECT A drop-down list
CHECKBOX Box that can be checked
RADIO Radio button
FILE Allows us to browse our computer for a file
BUTTON Button that allows us to click
SUBMIT Submit button
RESET Button that resets the input of the form
TEXTAREA Allows us to give multiple lines of input
Example:
<Html>
<Body>
<Form>
<Table>
<TR> <TD>User Name</TD> <TD> <Input Type='Text' MaxLength=16 size=20> </TD> </TR>
<TR> <TD>Desired Password</TD> <TD> <Input Type='Password' MaxLength=8 size=10> </TD> </TR>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- GUDUR Page 57
<TR> <TD>Gender</TD> <TD>
<TD>Area of intrests <Input
</TD> <TD>Type='Radio' Name='gender'
<Select Size=3 Multiple> Checked> Male
<Body>
<Form action='Login.php' method='GET'>
<?php
<Table>
if(trim($_GET['uname']=="essdc")&&trim($_GET['pwd']=="college"))
<TR> <TD>User Name</TD> <TD> <Input Type='Text' name='uname'echo MaxLength=16 size=20> </TD>
"<h1>You
</TR> are logged in successfully";
else
<TR> <TD>Desired Password</TD> <TD> <Input Type='Password' name='pwd' MaxLength=8 size=10>
</TD> </TR>
echo "<h1>Login Failed.......................................!";
<TR> <TD Align='Center'><Input Type='Submit' Value='Submit Data'></TD> <TD Align='Center'> <Input
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
POST:
When sending data using the POST method, data values are sent as standard input.
Nothing is appended to the URL (Uniform Resource Locator).
Example:
Welcome.php
<Html>
Login.php
<Html>
<Body>
<Body>
<Form action='Login.php' method='POST'>
<?php
<Table>
if(trim($_POST ['uname']=="essdc")&&trim($_POST ['pwd']=="college"))
<TR> <TD>User Name</TD> <TD> <Input Type='Text' name='uname' MaxLength=16 size=20> </TD>
echo "<h1>You are logged in successfully";
</TR>
else
<TR> <TD>Desired Password</TD> <TD> <Input Type='Password' name='pwd' MaxLength=8 size=10>
echo
</TD> "<h1>Login
</TR> Failed.......................................!";
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Another Example:
<Html>
<Body>
<TR> <TDAlign='Center'><InputType='Submit'Value='SubmitData'></TD><TD
CardDetails.php
<Html>
<Body>
<?php
In Web Applications, it is very common and vital to validate data that is entered into forms. We can
do this process at both client and server side. After receiving data from the client, server program
validates the data submitted by the client.
Data Validation:
Data Validation is the process of ensuring that some data might be correct data for a particular
application. It is the process of ensuring that users submit only the set of characters which the
application requires. It is not the process of ensuring that the data is accurate.
Most of the data that the scripts get from users will be textual data. So, we can write Regular
Expressions to check the textual data. Based on the results of the regular expressions, we can decide
whether data is valid or invalid.
Eg: If an application accepts username, we validate the username entered by the user is valid or not.
But we cannot guarantee that the username is a real name or not.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Example:
<Html>
<Body>
<Form action='CreateUser.php' method='POST'>
<Table>
<TR> <TD>Your Name</TD> <TD> <Input Type='Text' name='uname' MaxLength=16 size=20> </TD> </TR>
UserDetails.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<Html>
<Body>
<?php
$un =$_POST['uname'];
$crs =$_POST['course'];
$eml = $_POST['email'];
$valid=true;
if(trim($un)==""){
$valid = false;
if(trim($crs)=="") {
$valid = false;
if(trim($eml)=="") {
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<Html>
<Body>
<Form action='Page2.php' method='POST'>
<Table>
<TR> <TD>Your Name</TD> <TD> <Input Type='Text' name='uname' MaxLength=16 size=20> </TD>
</TR>
<TR> <TD ColSpan=2 Align='Center'><Input Type='Submit' Value='Goto Next Page'> </TD> </TR>
</Table>
</Form>
</Body>
</Html>
Page1.php
<Html>
<Body>
<Form action='Page3.php' method='POST'>
<Table>
<TR> <TD></TD> <TD> <Input Type='hidden' name='uname' value=" <?php echo $_POST['uname'] ?>" </TD> </TR>
<TR> <TD>Course</TD> <TD> <Select name='course'>
<Option> M.Sc </option>
<Option> M.C.A </option>
<Option> M.B.A </option>
</TD> </TR>
<TR> <TD ColSpan=2 Align='Center'><Input Type='Submit' Value='Goto Next Page'> </TD> </TR>
</Table>
<Html>
<Body>
<Form action='Final.php' method='POST'>
<Table>
<TR> <TD></TD> <TD> <Input Type='hidden' name='uname' value=" <?php echo $_POST['uname'] ?>" </TD> </TR>
<TR> <TD></TD> <TD> <Input Type='hidden' name='course' value=" <?php echo $_POST['course'] ?>" </TD> </TR>
<TR> <TD>e-Mail ID</TD> <TD> <Input Type='Text' name='email'> </TD> </TR>
<TR> <TD ColSpan=2 Align='Center'><Input Type='Submit' Value='Goto Next Page'> </TD> </TR>
</Table>
</Form> </Body>
</Html>
Page3.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<Html>
<Body>
<?php
$un =$_POST['uname'];
$crs =$_POST['course'];
$eml = $_POST['email'];
echo "<h1>Your Details:";
echo "<h2>".$un;
echo "<h2>".$crs; echo
"<h2>".$eml;
?>
</Body>
</Html>
Final.php
</Form>
</Body>
</Html>
Page2.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
5. Explain how to prevent multiple submission of a form at serverside Ans:
Users of the web sometimes may be impatient with the performance of the script while it is doing its
work. Because of this, the user may submit the form for multiple times by clicking the submit button
repeatedly.
This type of condition should be taken care because if the user sends some important details like credit
card details for payment, payment may be done for multiple times. So the script should take care about
this type of multiple submissions made by the user.
There are two approaches of solving this kind of problem, one is to solve at client side another is at
server side. As server does not have direct access to the user’s browser, it is something difficult to deal
with this type of problems.
Still we can handle this situation by using session-based method. Once the submit button is clicked, the
server logs the request from the individual user. If the user resubmits the request, then the server checks
the log and denies the request as request has already beensubmitted.
Example:
<Html>
<Body>
<Form action='CreateUser.php' method='POST'>
<Table>
<TR> <TD>Your Name</TD> <TD> <Input Type='Text' name='uname' MaxLength=16 size=20> </TD> </TR>
<TR> <TD> Course </TD> <TD> <Select name='course'>
<Option> Choose any course..........................................................................</Option>
<Option> M.Sc </Option>
<Option> M.C.A </Option>
<Option> M.B.A </Option>
</Select> </TD> </TR>
<TR> <TD>e-Mail ID</TD> <TD> <Input Type='Text' name='email' size=20> </TD> </TR>
<TR> <TD ColSpan=2 Align='Center'><Input Type='Submit' Value='Create User'> </TD> </TR>
</Table>
</Form>
</Body>
</Html>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Entry.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<Html>
<Body>
<?php
session_start(); if(!isset($_SESSION['processing']))
$_SESSION['processing']=false;
if($_SESSION['processing']==false)
$_SESSION['processing']=true;
for($i=1;$i<=100000;$i++) {
CreateUser.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
6. Explain how to prevent multiple submission of a form at client side Ans:
Users of the web sometimes may be impatient with the performance of the script while it is doing its
work. Because of this, the user may submit the form for multiple times by clicking the submit button
repeatedly.
This type of condition should be taken care because if the user sends some important details like credit
card details for payment, payment may be done for multiple times. So, the script should take care about
this type of multiple submissions made by the user.
There are two approaches of solving this kind of problem, one is to solve at client side another is at server
side. Handling multiple submissions at client-side is much simpler than at server-side. For this, we use
JavaScript.
Example:
<Html>
<Head>
<Script Language='JavaScript'>
function checkandsubmit() {
document.test.submitdata.disabled = true;
}
</Script>
</Head>
<Body>
<Form name='test' action='CreateUser.php' method='POST' onsubmit='checkandsubmit()'>
<Table>
<TR> <TD>Your Name</TD> <TD> <Input Type='Text' name='uname' MaxLength=16 size=20>
</TD> </TR>
<TR> <TD> Course </TD> <TD> <Select name='course'>
<Option> Choose any course..........................................................................</Option>
<Option> M.Sc </Option>
<Option> M.C.A </Option>
<Option> M.B.A </Option>
</Select> </TD> </TR>
<TR> <TD>e-Mail ID</TD> <TD> <Input Type='Text' name='email' size=20> </TD> </TR>
<TR> <TD ColSpan=2 Align='Center'><Input Type='Submit' Value='Create New User'
name='submitdata' onClick='checkandsubmit()'> </TD> </TR>
</Table>
</Form>
</Body>
</Html>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Entry.php
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
7. Explain how to connect to the MySQL database using PHP code
Ans:
To do any work with MySQL database, we must open a link and connect to it. PHP performs this task
very efficiently and quickly. After connecting to the database, we can perform any type of database
operations like creating a table, inserting data into the table, updating or deleting the data and
retrieving the data when we are required. Once our work is over, we must close the connection
which is opened earlier.
Connecting to the MySQL Database:
We can connect to the MySQL database using the method called mysqli_connect() which takes
some parameters to connect to the database. These parameters are related to login information. The
prototype is as follows:
resource mysqli_connect(string server, string username, string password, string
dbname);
Here, server specifies the location where the database is located, username and password specify
the username of the database and password associated with that database and dbname specifies the
actual database name.
Closing the connection:
After finishing all the database operations, we must close all the opened connections using the
method called mysqli_close(). The prototype is as follows:
bool mysqli_close(string databasename);
Example:
Connection.php
Output: <Html>
<Head
>
<?php
PHP Material for M.Sc C omp.Sci III semester :: S.V ARTS & ENCE COLLEGE- GUDUR Page 70
$hostname = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "demo";
else
$hostname = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "demo";
$stmt = "Create Table Student(sid int(3), sname varchar(20), course varchar(8))"; if(mysqli_query($con, $stmt))
echo "<h6>Table Created"; else
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Ans:
Once we have a connection to the database, we can query the database. We query the
MySQL database using Structured Query Language (SQL) for building communication with the
database. Queries may be in different forms, that is each query may require different types of
arguments.
SQL allows us to perform common operations such as creating a table structure, altering the table
structure, inserting data into the database, selecting the data from the database, updating the data
in a table and deleting data from the database.
To perform a query in PHP, we can use the function mysqli_query(). The prototype of the function is
as follows.
resource mysqli_query(resource, query)
The above function returns a resource as a result set containing the results after executing the query
passed to the function. To process individual rows from the result set, we use the method
fetch_array() or fetch_assoc().
Example:
<Html>
<Head>
<?php
$hostname = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "demo";
if($con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname ))
echo "<h2>Connected to the database";
else
echo "<h2>Could not connect to the database";
$stmt = "Create Table Student(sid int(3), sname varchar(20), course varchar(8))";
if(mysqli_query($con, $stmt))
echo "<h6>Table Created"; else
echo "<h6>Table Creation Failed........................................!";
$stmt = "Insert Into Student Values(100,\"Anil Kumar\",\"M.C.A\")";
mysqli_query($con, $stmt);
$stmt = "Insert Into Student Values(101,\"Bharath Kumar\",\"M.Sc\")";
mysqli_query($con, $stmt);
$stmt = "Insert Into Student Values(102,\"Chandra Sekhar\",\"M.Com\")";
mysqli_query($con, $stmt);
$stmt = "Insert Into Student Values(103,\"David\",\"M.B.A\")";
mysqli_query($con, $stmt);
$stmt = "Select * From Student";
$rs = mysqli_query($con, $stmt); if($rs-
>num_rows>0)
while($row=$rs->fetch_array())
echo "<h3>".$row['sid'].$row['sname'].$row['course'];
mysqli_close($con);
?>
</Head>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
10. Explain how to modify data in the MySQL database
Ans:
Once we have a connection to the database, we can query the database. We query the MySQL
database using Structured Query Language (SQL) for building communication with the database.
Queries may be in different forms, that is each query may require different types of arguments.
SQL allows us to perform common operations such as creating a table structure, altering the table
structure, inserting data into the database, selecting the data from the database, updating the data
in a table and deleting data from the database.
To perform a query in PHP, we can use the function mysqli_query(). The prototype of the function is
as follows.
resource mysqli_query(resource, query)
Example:
<Html>
<Head>
<?php
$hostname = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "demo";
$stmt = "Update Student set sname=\"Bharath Chandra\" where sid=101"; mysqli_query($con, $stmt);
echo "<h3>Row is updated"; mysqli_close($con);
?>
</Head>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
11. Explain how to delete data from the MySQLdatabase
Ans:
Once we have a connection to the database, we can query the database. We query the MySQL
database using Structured Query Language (SQL) for building communication with the database.
Queries may be in different forms, that is each query may require different types of arguments.
SQL allows us to perform common operations such as creating a table structure, altering the table
structure, inserting data into the database, selecting the data from the database, updating the data
in a table and deleting data from the database.
To perform a query in PHP, we can use the function mysqli_query(). The prototype of the function is
as follows.
resource mysqli_query(resource, query)
Example:
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
<Html>
<Head>
<?php
$hostname = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "demo";
else
?>
</Head>
<Body>
</Body>
MVC, which stands for Model-View-Controller, is a really good way to develop clean,
scalable, powerful and fast applications in the least amount of time and with the least
effort.
PHP is an open source programming language that was developed in 1994 by Rasmus
Lerdorf. PHP originally stood for Personal Home Pages but now stands for Hypertext Pre-
Processor, which is a recursive acronym. It is a loosely typed server-side scripting
language used to build Web applications. A scripting language is a language that does not
need to be compiled before use. And ‘loosely typed’ languages are those in which there is
no need to define the type of a variable.
Today, more than 20 million domains use PHP, including Facebook and Yahoo. PHP
is easily embedded with HTML, and is used to manage dynamic content and the
databases of websites or, we can say, Web applications. We can use PHP with many
popular databases like MySQL, PostgreSQL, Oracle, Sybase, Informix and Microsoft SQL
Server.
How PHP works on servers
When a client (browser) sends a request for a PHP page to the server, the server reads the
requested file from the disk (storage) and sends this file to the interpreter. The interpreter
then runs the PHP code, fetches the DB data (if required) and puts it into HTML tags. Once
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE GE- GUDUR Page 75
the interpreter completes its tasks, it sends the result back to the server, which sends
this data to the client (browser) that made a request for this page.
MVC architecture with PHP
The Model-View-Controller concept involved in software development evolved in the late
1980s. It’s a software architecture built on the idea that the logic of an application should
be separated from its presentation. A system developed on the MVC architecture should
allow a front-end developer and a back-end developer to work on the same system
without interfering with each other.
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page
Model:
Model is the name given to the component that will communicate with the database to
manipulate the data. It acts as a bridge between the View component and the Controller
component in the overall architecture. It doesn’t matter to the Model component what
happens to the data when it is passed to the View or Controller
components. The code snippet for running first_model.php is:
<?php
class Model
{
public $string;
public function construct()
{
$this->string = “Let’s start php with MVC”;
}
}
?>
View
The View requests for data from the Model component and then its final output is
determined. View interacts with the user, and then transfers the user’s reaction to the
Controller component to respond accordingly. An example of this is a link generated by
the View component, when a user clicks and an action gets triggered in the
Controller. To run first_view.php, type:
<?php
class
View
{
private $model;
private
$controller;
public function construct($controller,$model)
{
$this->controller = $controller;
$this->model = $model;
}
public function output()
{
return “<p>” . $this->model->string . “</p>”;
}
}
?>
Controller
The Controller’s job is to handle data that the user inputs or submits through the forms,
and then Model updates this accordingly in the database. The Controller is nothing
without the user’s interactions, which happen through the View
component. The code snippet for running first_controller.php is:
<?php
class Controller
{
private $model;
public function construct($model)
{
$this->model = $model;
}
}
?>
PHP Material for M.Sc Comp.Sci III semester :: S.V ARTS & SCIENCE COLLEGE- Page