Colour
Colour
XML Basics
•• "Review Q",estions ••
"I. Explain the anatomy of an XML document with example.
4. What is XML declaration ?
3. What are attributes ? How attributes are different from elements ? Where attributes should be
used ? Explain with example.
4. Explain element markup and attribute markup with example.
S. What are the various components of XML document ? Explain.
a. State the various components of an element.
7~ Differentiate between XML and HTML.
8. Write a short note on empty element.
J
.., INTRODUCTION
PHP was started out as a small open source project by Rasmus Lerdorf way back in 1994.
PHP is a recursive acronym for "PHP : Hypertext Preprocessor". It is a server-side scripting
language designed specifically for web development. It is used to manage dynamic. content,
databases, session tracking, even build entire E-commerce sites. Websites like www.facebook.com,
www.yahoo.com are built on PHP. PHP can be easily embedded in HTML files (as shown in
Fig. 2.1) and HTML codes can also be written in a PHP file.
<html>
<body>
Hello, today is <?=date('l, F jS, Y'); ?>.
</body>
</html~
Fig. 2.1. PHP embedded in HTML.
In the example above the PHP code <? =date('l, F jS, Y'); ? > has been embedded in HTML
code. This code has the date function which displays the date of the local machine. The following
parameters of date functionare used :
1. I (lowercase 'L') - A full textual representation of a day.
2. F - A full textual representation of a month (January through December).
3. j - The day of the month without leading zeros (1 to 31).
4. S - The English ordinal suffix for the day of the month (2 characters st, nd, rel!or
tho Works well with j).
5. Y ~ A four digit representation of a year.
42
PHP
The output of the above code is given below
The thing that differentiates PHP with client-side language like HTML is, PHP codes are
executed on 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. The Fig. 2.3 below
explains the concept of execution of PHP code.
Response
(html file)
Host for
www.webqoel.com
Software
Fig. 2.3. Execution of PHP script.
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. It is integrated
with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix,
and Microsoft SQL Server, thus making easy for the developers in their development work.
Almost all browsers support PHP. Also, PHP supports a large number of major protocols such
as POP3, !MAP and LDAP. PHP syntax is C-Like .
3. PHP is cross-platform, hence you can easily develop and move/deploy your PHP code/
project to almost all the major operating systems like Windows, Linux, Mac OSX etc.
Passed straight
Static web page to browser Browser
(.htm or .html)
.....•.
...-.,~.
,
2. After installation, start XAMPP control panel and run Apache and MySQL as shown in
Fig. 2.7.
~k~otJi¥*"~~,H~~~~~,~~","~~k>6¢>!MIr.!e~b:!If\M'I.jN
~iJOJ~~~1\~)'(M~~~~.I:t~wmt<I,~~~~~~~~~~
~j,:'~~~l'!'I~~~~~~l;:A~lt$~'>'I1~ffiPf~_,_~:t~1::~~~f'~~Mi'«~w#"'>~tA:.Wtl$'
~AMr»i>t<m;::.A~~_~~~tI~*,m~{W{';':ilJ~t{:\l' r~1:;,l{b)fl
COmmunity
<?php
$txt = "Hello world!";
$x=5;
$y = 10.5;
echo $txt;
echo '"<br>";
echo $x;
echo "<br>";
echo Sy;
1>
</body>
[<zhtml>
Fig. 2.9. Code of PHP.
4. Save the file as "my_first code.php", in "htdocs" folder as shown below
aa favicon 7j16/Z()15 9;02PM leon
• index 7f16/2()159:02PM PHpfife
ttl New Text Document
Hello world!
5
10.5
Fig. 2.11. Output of your first PHP program.
- Eagle's Web Development Using PHP
6. "htdocs" folder is the folder on your local server. When you request from any browser
for the LOCALHOST, the server responds and the file requested is shown. If you open
this file directly in browser, the output will be plane file and no processing will be
done on the server.
7. From here onwards, run all the codes of PHP like the demonstration given above.
APte : Write the above code in notepad and save the file with" .php" extension, then
open browser and open localhost server of your XAMPP server. Give the path of the file you
saved and view the output as already explained above.
2. SGML or Short HTML tags : These are the shortest option to initialize a PHP code.
The script starts with <? and ends with ? >. This will only work by setting the short_open_tag
setting in php.ini file to 'on'. For example :
<7
#. Here echocornrnand will only work if
# setting Is done assald before
echo "Hello, world!";
?>
APte : The option of short_open_tag setting in php.ini file must be disabled to parse
XML with PHP because the same syntax is used for XML tags.
PHP
3. HTML script tags: These are implemented using script tags. This syntax is removed
in PHP 7.0.0. So, its no more used. For example :
<script language="php">
echo"hello world!";
</script>
4. ASP style tags: To use these we need to set the configuration of php.ini file. These
are used by Active Server Pages to describe code blocks. These start with < % and end with
% >. For example :
<%
# Can only be written ifsetting is turned on
# to allow %
echo"hello world";
%>
.2.4.2. Commentsin PHP
A comment is something which is ignored and not read or executed by PHP engine or the
language as part of a program and is written to make the code more readable and understandable.
These are used to help other users and developers to describe the code and what it is trying to
do. It can also be used in documenting a set of code or part of a program. You must have
noticed this in above sample programs.
PHP supports two types of comment :
1. Single line comment : As the name suggests these are single line or short relevant
explanations that one can add in their code. To add this, we need to begin the line with (1/)
or (#). For example:
<?php
II This is a single line comment
II These cannot be extended to more lines
echo "hello worldlll":
# This is also a single line comment
?>
Output:
hello wcrlell!
2. Multi-line or Multiple line comment : These are used to accommodate multiple lines
with a single tag and can be extended to many lines as required by the user. To add this, we
need to begin and end the line with (/*...*/). For example:
<?php
1* This is a multi IIn@eemment
In PHP vartables ar written
by adding a $ sign at the beginning. "if/
- $eagle= "hello children!";
echo $eagle;
7>
Eagle's Web Development Using PHP
Output:
hello children!
</body>
«/htrnl>
Output:
252525
Notice: Undefined variable: VARIABLE in
C:\xampp\btdocs\xmlpbp\variable.pbp on
line 16
Fig. 2.12. Output for code above•
if(3==2+1)
{
print("Good - I haven't totally");
print("lost my mind.<br>");
}
• 2.5. VARIABLES
Variables is a way to store information in the PHP program. A variable can have a short
name (like x and y) or a more descriptive name (age, car_name, total_volume). In PHP, a
variable starts with the $ sign, followed by the name of the variable as shown below :
<?php
$txt =
"Hello world!";
$x = 5;
$y = 10.5;
?>
El9lc'. Web Development Using PHP
Here, $txt, $x and $y all are variables. After the execution of the statements above, the
variable $txt will hold the value 'Hello world!', the variable $x will hold the value '5' and the
'variable $y will hold the value '10.5'.
/dPtel: When you assign a text value to a variable, put quotes around the value.
/dPte 2 : Unlike other programming languages, PHP has no command for declaring a
variable. It is created the moment you first assign a value to it.
• 2.5.1. Rules for PHP VIriabIes
Rules for PHP variables are as the following :
1. A variable starts with the $ sign, followed by tlte name of the variable.
2. A variable name must start with a letter or the underscore character.
3. A variable name cannot start with a number.
4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
5. Variable names are case-sensitive ($age and SAGE are two different variables).
6. Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
7. Variables do not need, to be declared before assignment.
8. 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.
• 2.5.2. Data types of variables In PHP
PHP has a total of eight data types which are used to construct variables given in Table
2.1 below.
Table 2.1. Data types or variables.
, <?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
=
echo "$many + $many_2 $few <br>":
?>
</body>
</html>
Output:
2.28888 + 2.21112 = 4.5
7>
</body>
e/html»
Output:
bool(false). The width needs to be
a non-zero number
var_dump() - gives the data type of
variable and its value. In this
example, "=: =:" acts as Boolean
expression, when the expression is
"False" only then the Echo statement
will be executed.
Eagle's Web Development Using PHP
Example 2 :
<!DOCTVPE htrnl>
<htrnl>
<body>
<?php
$cars =
array("Volvol,IBMWI,IToyota");
echo $cars[l];
?>
</body>
-c/html>
Output:
BMW
It is the value at place 1 of the array
$cars.
II create an object
$var = new Cart):
II show object properties
echo $var->model;
?>
</body>
</html>
Output
VW
Resources These are special variables that <!DOCTVPE html>
hold references to resources <htrnl lang="en">
external to PHP (such as database
connections). <head>
<title> PHP Resources</title>
</head>
<body>
<?php
II Open a file for reading
$handle = fopen("note.txt", "r").
var_dump($handle);
?>
</body>
</html>
Output:
reseurcetz) of type (stream)
~tel: The PHP echo statement is often used to output data to the screen.
fdpte 2 : The var_dump() function is used to dump information about a variable. This
function displays structured information such as type and value of the given variable. Arrays
and objects are explored recursively with values indented to show structure. This function is
also effective with expressions.
• 2.5.3. Variable scope
Variable scope is known as its boundary within which it can be visible or accessed from
code. In other words, it is the context within which a variable is defined. When a variable is
accessed outside its scope it will cause PHP error undefmed variable, There are three scopes
available in PHP as shown in the Fig. 2.13 below :
1. Local scope variables : A local scope is a restricted boundary of a variable within which
code block it is declared. That block can be a function, class or any conditional span. The
variable within this limited local scope is known as the local variable of that specific code block.
PHP
Example:
<!DOCTYPE htrnl>
.<html>
'<body>
<?php
function myTestO {
$x = 5; II local scope
echo "<pxVariable x inside function is: Sx c/p>":
myTestO;
</body>
</html>
Output:
2. Global scope variables: As its name, the global scope provides widespread access to
the variable declared in this scope. Variables in global scope can be accessed from anywhere
from outside a function or class independent of its boundary.
Example:
<!DOCTYPE html>
<htrnl»
<body>
<?php
$x = 5; II global scope
function myTestO {
II using x inside this function will generate an error
. echo "<pxVariable x inside function is: $x</p>";
} myTest();
Output:
I:i - - U'
<?php
$x = 5; II global scope
function myTestO {
II using x inside this function will generate an error
. Global $x; <==================~: ~G~IO~ba~l~ke~yw~o~rd~a~dd~e~dJI
echo" <p>Variable x inside function is: $x</p>";
myTestO;
</body>
</html>
Output:
Variable x inside function is : 5
Variable x outside function is : 5
PHP also stores all global variables in an array called $GLOBALS[index).The index holds
the name of the variable. This array is also accessible from within functions and can be used
to update global variables directly. For example :
<!DOCTYPE htrnl>
<htrnl>
<body>
<?php
$x = 5;
$y = 10;
function myTestO {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
myTestO;
Eagle's Web Development Using PHP
echo $y;
?>
</body>
</html>
Output
15
3. Static variables (Local scope) : A static variable is again a variable with local scope. But
the difference with the regular local variable is that it is not destroyed outside the scope boundary.
A variable can be defmed by using the 'static' keyword inside a function. For example:
<!DOCTVPE html>
<html>
<body>
<?php
function myTestO {
static $x = 0;
echo $x;
$x++;
rnyf'estf):
echo "<br>":
myTest();
echo "<br>":
myTestO;
?>
</body>
</html>
Output
o
1
2
Here, the variable "x" is declared in the function "my'I'esu)" using static keyword. And
the function "my'I'esu)" has been called thrice. Thus, every time the incremented value of "x"
is coming is the output. Therefore, the scope of "x" is inside the function as well as outside
the function.
below is a typical statement in PHP, which in this case assigns a string of characters to a variable
called $greeting.
$greeting = "Welcome to PHP!";
In PHP, multiple statements can be executed simultaneously (under a single condition or
loop) by using curly-braces ({}). This forms a block of statements which gets executed
simultaneously.
<?php
$var= 50;
if($var> O){
echo("Positive as \n");
echo("greater than 0");
?>
Output
Positive as
greater than 0
.. 2.7. OPERATORS
An operator is used to perform operations on one or more values and yields another value.
Operators can be grouped according to the number of values they take. Unary operators take
only one value, for example the logical not operator (!) or the increment operator (+ +). Binary
operators take two values, such as the arithmetical operators + (Plus) and - (minus). Finally,
there is a single ternary operator, ? :, which takes three values ; this is usually referred to
simply as "the ternary operator". Thus, PHP provides us with many operators to perform such
operations on various operands or variables or values. These operators are nothing but symbols
needed to perform operations of various types. Given below are the various groups of operators
provided by PHP :
1. Arithmetic operators
2. Logical or Relational operators
3. Comparison operators
4. Conditional or Ternary operators
5. Assignment operators
6. Array operators
7. Increment/Decrement operators
8. String operators.
1. Arithmetic operator : The arithmetic operators are used to perform simple mathematical
operations like addition, subtraction, multiplication etc. Table 2.2 shows the list of arithmetic
operators along with the syntax and operations, that PHP provides.
Eagle's Web Development Using PHP
Example:
<!DOCTYPE html>
<html>
<body>
<?php
il variable 1
$x =
29;
II variable 2
$y = 4;
</body>
</html>
Output
33
25
116 .
7.25
1
. ,0.
PHP
2. Logical or Relational operators :. These .are basically used to operate with conditional
statements and expressions. Conditional statements are based on conditions. Also, a condition can
either be met or cannot be. met so the result of a conditional statement can either be true or false.
Table 2.3 shows the logical operators along with their syntax and operations, that PHP provides :.
Example:
<!DOCTYPE html>
.<htrnl>
<body>
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success <br>":
if ($x == 50 or $y == 20)
echo "or Success <br>";
if ($x == 50 xor $y == 20)
echo "xor Success <br>":
if ($x == 50 && $y == 30)
echo "&& Success <br>":
if ($x == 50 II $y == 20)
echo "IISuccess < br> ";
if (!$z)
echo "! Success <br>":
?>
</body>
</html>
- Output
and Success
or Success
Eagle's Web Development Using PHP
xor Success
&& Success
II Success
! Success
3. Comparison operators : These operators are used to compare two elements and outputs
the result in Boolean form. Table 2.4 shows the comparison operators along with their syntax
and operations, that PHP provides :
Table 2.4. Comparison operators.
Example:
<!DOCTYPE htrnl»
<html>
<body>
<?php
$a = 80;
$b = 50;
$c = "80";
displays structured information such as type and value of the given variable. */
-
/*The var_dumpO function is used to dump information about a variable. This function
$x =5;
$y :;: 1Q;
Example:
<!DOCTYPE htrnl> I
<htrnl>
<body>
<?php
$x =
-12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
echo "<br>":
II variable $color is "red" if $color does not exist or is null
echo $color = "YELLOW" ?? "red";
?>
</body>
</html>
Output:
The number is negative
YELLOW
5. Assignment operators : These operators are used to assign values to different variables,
with or without mid-operations.Table 2.6 shows the assignment operators along.with their syntax
and operations, that PHP provides us. .
PHP
= Assign
Table 2.6. Assignmentoperators.
$x = $y
-
Operand. on the left obtains the value of the
operand on right.
+= Add then $x += $y Simple Addition same as $x = $x + $y ..
Assign
Subtract then $x -= $y Simple subtraction same as $x = $x - $y.
Assign
,*= Multiply then $x *= $y Simple product same as $x = $x * $y.
Assign
/= Divide then $x /= $y Simple division same as $x = $x / $y.
Assign (quotient)
%= Divide then Assign $x %= $y Simple division same as $x = $x % $y.
(remainder)
Example:
<!DOCTYPE html>
chtml>
<body>
<?php
II simple assign operator
$y =
75;
echo $y, "<br>";
II add then assign operator
$y = 100;
$y += 200;
echo $y, <br> ";
II
echo $y;
?>
</body>
</html>
Output
75
300
60
600
20
o
6. Array operators: These operators are used in case of arrays. Table 2.7 shows the array
operators along with there syntax and operations, that PHP provides.
Table 2.7. Array operators.
Example:
<!DOCTYPE htrnl»
<html>
<body>
<?php
$x :;;;arr€ly("k" ;;:;:> IICar", iliff ;;:;:> IIBlke");
$y :;;;iilfrGly(II€1" :;;;:;;'"Train", "b" ;;;:> "Plane");
var=dump($x + $y); echo lI<br>lI;
viilr=dump($x 5;;:; $y); echo "<br>ff;
PHP
var_dump($x
var_dump($x
var_dump($x
!= $y);echo "<br>";
<> $y); echo "<br>":
=== $y); echo "<br>":
-
var_dump($x !== $y);echo "<br>":
?>
</body>
</html>
Output:
array(4)
{ ["k"] = > string(3) "Car"
["I"] = > string(4) "Bike"
["a"]=> string(S) "Train"
["b"] = > string(S) "Plane"
bool(false)
bool(true)
bool(true)
bool(false)
boolttrue)
7. Increment/Decrement operators : These are called the unary operators as they work on
single operands. These are used to increment or decrement values. Table 2.8 shows the increment
and decrement operators, that PHP provides us.
Table 2.S. Increment and decrement operators.
Example:
<!ElOCTYPE htrnls
chtml>
<body>
<?php
$x ;;; 2;
echo + +$x, "First increments then prints \n";
echo $x, "cbr>":
- $x = 2;
echo $x++, "First prints then increments \n";
echo $x, "< br> ";
Eaglc's Web Development Using PHP
$x = 2;
echo -$x, "First decrements then prints \n";
echo $x, "<br>":
$x =2;
echo $x-, "First prints then decrements \n";
echo $x;
?>
</body>
</html>
Output:
3 First increments then prints 3
2 First prints then increments 3
1 First decrements then prints 1
2 First prints then decrements 1
8. StJjng operators : PHP has two operators that are specially designed for strings as shown
in the Table 2.9 below.
Table 2.9. String operators.
Example:
<!OOCTYPE htrnl>
-chtml>
<body>
<?php
$x = "Publisher";
$y = "Eagle";
$z = "Prakashan!!!";
echo $x.$y.$z, "< br>":
$x.= $y.$z;
echo $x;
?>
PHP
</body>
</html>
Output:
-
PublisherEaglePrakashan!!!
PublisherEaglePrakashan!!!
False
Example:
<?php
$x= 12;
Eaglc', Web Development Using PHP
if($x> 0) {
echo'The number is positive";
?>
Output
The number is positive.
2. ir...else statement: To execute a code when the condition is false. This is where "else"
comes to play. Thus, if a condition is TRUE then if block gets executed, otherwise else block
gets executed. The flowchart below depicts the working of if-else statement.
False
elsel
II if FALSI! then execute this code
Example:
<?php
$x;: -12;
if($x> 0) {
eehc'Tbe number is positive";
else{
PHP
?>
echo'The number is neqative": -
Output
The number is negative.
elseif {
/1 if TRUEthen execute this code
elself {
// it TRUEthen execute this code
else {
//It FALSEthen execute this code
Eagle's Web Development Using PHP
Example:
<?php
$x= "August";
if($x= = "January") {
echo"Happy Republic Day";
elseif($x== "August") {
. echo"Happy Independence Day!!!";
else{
echo"Nothing to show";
?>
Output
Happy Independence Day!!!
4. Switch statement: The "switch" performs in various cases t.e., it has various cases to
which it matches the condition and appropriatelyexecutes a particular case block. It first evaluates
an expression and then, compares with the values of each case. If a: ease matches then the same
case is executed. To use switch, we need to get familiar with two different keywords namely ;
break. and default. .
(i) The break. statement is used to stop the automatic control flow into the next cases and
exit from the switch case.
(ii) The default statement contains the code that would execute if none of the cases match.
The flowchart below depicts the switch statement.
switCh(n) .I ,
case statemenn: , ,
code to be executed if n==statementl;
break;
case statement2:
, .' code to b~executed if 'n= =statement2;
, .'
k ' ,
'brea''"
default
"'f code tcbeexecuted if n:!= any case;
. )'~-o"- .- ",' ,_'. .
'Example ':
< ?php . h" , .:
$n= "February";
switch($n) {
case"January":
echo"Its January";
break;
case'February": , .~ , ,:.. I') • • " I',· ~,
. break
0" ' :. "
." ,,(~I:~'
..:( ~.:
case'March": ,,- .~
.. ,~
echo'Its March"; .,
, break;
case"April": ~!" , J •
echo'tts April";
break;' , .. "I .~-.~,.,- ,. 1.~-"
~;... ;.
,ca~e"May": " , , I/,~;
" -';.,
, , echc'Its May"; ,; i
break;
Eagle's Web Development Using PHP
case'June":
echo"Its June";
break;
caseJuly":
echo"Its July";
break;
case'Auqust":
echo"Its August";
break; .
case"September":
echoIts September";
break;
case"October":
echo"Its October";
break;
case'Novernber":
echo'Its November";
break;
case"December":
echo'Its December";
break;
default:
echo"Doesn't exist";
7>
Output
Its February.
., 2.9, LOOPS
Loops in PHP are used to execute the same block of code .a specified number of times.
PHP supports following four loop types :
1. for - loops through a block of code a specified number of times.
2. while - loops through a block of code if and as long as a specified condition is true.
3. do.••while - loops through a block of code once and then repeats the loop as long as
a special condition is true.
4. foreach - loops through a block of code for each element in an array.
1. for loop: This type of loops is used when the user knows in advance, how many times
the block needs to execute. That is, the number of iterations is known beforehand. This type
of loops is also known as entry-controlled loop. There are three main parameters to the code,
PHP
-
namely the initialization, the test condition and the counter. The flowchart below explains the
concept.
In for loop, a loop variable is used to control the loop. First initialize this loop variable to
some value, then check whether this variable is less than or greater than counter value. If
statement is true, then loop body is executed and loop variable gets updated. Steps are repeated
till exit condition comes.
(,) Initialization expression : In this expression, we have to initialize the loop counter to
some value. For example, $num = 1;
(i,) Test expression : In this expression, we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update expression otherwise
we will exit from the for loop. For example, $num < = 10;
(ii,) Update expression: After executing loop body this expression increments/decrements
the loop variable by some value. For example, $num + = 2;
Example:
<?php
II code to Illustrate for loop
for($num... 1; snume .. 10; $num+;;; 2) {
echo "$num<br>lI;
Eagle's Web Development Using PHP
, OUtput' :
1
3
5
7
9
2. while loop : The while loop is also an entry control loop like for loops i.e., it first
checks the condition at the start of theIoop and if it's true then it enters the loop and executes
the block of statements"and goes on, executing it as long as' the condition'holds true. The concept
is showri in,the flowchart given below.
False
Example:
<?php
II PHPcode to illustrate while loops,
,$num= 2;' "
while($num< 12) { ,
$num+= 2;
echo$num, "<br>";
}
1>
Output
4
6 I.:
" 8
10
12
PHP
3. do-while loop : This is an exit control loop which means that it first enters the 'ioop,
executes the statements and then' checks the c~ndition. Therefore, a statement is executed at least
once on using the do...while Ioop. After executing o~ce, 'the program is execued as' long as
the condition holds.true. The flowchart below depicts the concept. . .
?>
Output :,
4
6
8
10
12
Eaglc', Web Development U.lng PHP
This code would show the difference between while and do...while loop.
<7php
II PHP code to illustrate the difference of two loops
$num= 2;
II In case of while
while($num != 2) {
echoIn case of while the code is skipped";
echo$num, "\n";
I I In case of do ...while
do{
$num++;
echo"The do ...while code is executed atleast once";
} while($num != 2);
7>
Output
The do ...while code is executed atleast once.
4. foreach loop : The foreach loop provides the easiest way to iterate the array elements.
It works on array and objects both. The foreach loop though iterates over an array of elements,
the execution is simplified and finishes the loop in less time comparatively. It allocates temporary
memory for index iterations which makes the overall system to redundant its performance in
terms of memory allocation. The concept is shown below in Fig. 2.23.
Iterate
False
,
foreach ($array as $element) {
II PHP Code to be executed
or
foreach ($array as $key = > $element) {
II PHP Code to be executed
Example:
<?php
$employee= array(
"name"= > "Robert",
..email ..=>"[email protected] ",
"age"=> 18,
"gender"=> "male"
};
?>
Output
name: Robert
email: [email protected]
age: 18
gender: male
In addition to these looping statements, there are break and continue statement in PHP to
forcefully stop or continue a loop. These are given as under;
The PHP break keyword is used to terminate The PHP continue keyword is used to halt
the execution of a loop prematurely. the current iteration of a loop but it does not
The break statement is situated inside the terminate the loop.
statement block. It gives you full control and Just like the break statement the continue
whenever you want to exit from the loop you statement is situated inside the statement block
can come out. After coming out of a loop containing the code that the loop executes,
immediate statement to the loop will be preceded by a conditional test. For the pass
executed. encountering contlnue statement, test of the
loop code is skipped and next pass starts.
Loop
False
False
Example: Example. :
<html> <html>
<body>
<body>
<?php
<?php $array = array(l, 2, 3, 4, 5);
$i =0;
foreach($array as $value){
while($i < 10){ if($value ==3)continue;
$i++; echo "Value is $value <br/>":
if($i ==3)break;
} ?>
echo ("Loop stopped at i = $i"); </body>
?> </html>
Output: .
</body>
Value is 1
</html>
Value is 2
Output: Value is 4
Loop stopped at i = 3 Value is 5
.. 2.10. ARRAYS
Arrays in PHP is a. type of data structure that allows us to store multiple elements of similar
data type under a single .variable thereby saving us the effort of creating a different variable
. . I ' " ..
PHP
be accessed using their index or key. Suppose we want to store five names and print them
-
for every data. The arrays are helpful to create a list of elements of similar types, which can
accordingly. This can be. easily done by the use of five different string variables. But if instead
of five, the number rises to hundred, then it would be really difficult.for the user or·developer
to create so much different variables. Here array comes into play and helps us to store every
element within. a single variable and also allows easy access using an index or. a key. An array
.is created using, an ~ayO. function in PHP.
There.are basically three types ?f arrays in PHP :
.'1. fud:exed or Numeric arrays ; An array with a numeric index where values are stored
linearly." :. .. . .
2. ASsociative arrays : An array with a string index where instead of linear storage, each
value can be assigned a specific key.
3. Multidimensional arrays : An array which contains single or multiple array within it
and can be accessed via multiple indices.
1. Indexed or Numeric arrays: These arrays can store numbers, strings and any object
but their index will be represented by numbers. By default, array index starts from zero. These
arrays can be created 'in twodifferent ways as 'shown in the following example:
~?php '.. .
.?>
Eagle's Web Development Using PHP
Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV
Traversing : We can traverse an indexed array using loops in PHP. We can loop through
the, indexed array in two ways. First by using for loop and secondly by using foreach as shown
in example given below.
<!DOCTVPE html>
<html>
<body>
<?php
II Creating an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
1>
</body>
</html>
PHP
Ii"
-_p;-
_x-- _,
Output
Looping using foreach:
Zack
Anthony
Ram
Salim
Raghav
The number of elements are 5
Looping using for:
Zack
Anthony
Ram
Salim
Raghav
2. Associative arrays : The associative arrays are very similar to numeric arrays in terms
of functionality but they are different in terms of their index. Associative array will have their
index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.
/OPte : pon't keep associative array inside double quote while printing otherwise it would
not return any value.
Keys Values
Fig. 2.24. Associative array.
Eagle'. Web E)eveloj)lnent Using PHP.
The difference between' numeric array and associative array can be shown' in the -following
Fig. 2.25. " ."
Numerical index
,String Index
AssOCiativearray
Fig. 2.25. Difference between numerical and a8soclatlve array•.
Example:
chtml>
<body>
<?php
/* First method to create associate array. *1
$salaries=array("mohammad"= >2000,"qadir"= >1000,"zara"= >500);
</body>
</html>
Output:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Traversing associative arrays : We can traverse associative arrays in Ii similar' way, did in
numeric arrays using loops. We can loop through the associative array in two ways. 'First'by
using for loop, and secondly by using foreach.' ,
Example:
<,!DOCTYPE htrnl>
<html>
<body> .
I,
<?p,hp
1/ Creating an associative array
$name_one, = array("Zack"=>"Zara", "Anthony"=>"Ani',
"Ram"=>"Rani", "Salim"=>"Sara",
,
"Raqhav"= >"Ravina"); I
,
i
!
II Looping through an array using foreach
echo "Loopingusing foreach: <br>":
foreach ($~ame_one as $val => $val_value){
. - j
echo "Husband is ".$val." and Wife is ".$val_value."<br>"; ,
?>
</body>
</html>
Output:
looping using foreach :
Husband is Zack and Wife is Zara
Husband is Anthony and Wife, is Any ,
Husband is Ram,and Wife is Rani , ,
I
Husband is Salim and Wife is Sara
Husband is Raghav and Wife is Ravina
Eagle's Web Development Using PHP
<?php
/ / Defining a multidimensional array
$favorites = array(
array(
"name" ::;> "Dave Punk",
"mob" = > "5689741523",
..email .. ::;> [email protected] ...
),
array(
"name" ;;;> "Monty Smith",
"mob" ;;;> "2584369721",
.•email!.=> [email protected] ",
),
array(
"name" ;:;;:;."John Flinch",
"mob" ",;;:;."9875147536",
..emailu :;;;) [email protected] ...
);
II Accessing elements
echo "Dave Punk emaiHd is: I' • $favorites[O][..small..l.1/ <br>";
. echo "John Flinch mobile number is;" . $favorites[2]["mob"];
?>
</body>
</html>
Output:
Dave Punk email-idis:[email protected]
John Flinch mobile number is: 9875147536
.<?php
II Defining a multidimensional array
$favorites =array(
=
"Dave Punk" > array(
"mob" => "5689741523",
. ..email.. :;:> [email protected] ...
),
"Monty Smith" => array(
"mob" = > "2584369nl'~,
..email.. => [email protected]".
),
"John Flinch// :;:)0 array(
"mob" =)0 //9875147536//,
llemailll=>[email protected] ",
)
);
/1 Using for and foreach in nested form
$keys :;: array_keys($favorites);
for($i :;;;0; $i < c:ount($favorites); $i++) {
echo $keys[$i] , "<br>"
foreach($favorites[$keys[$i]l as $key :;:> $value) {
echo $key . // : // . $value . //<br>//;
echo "<br>//;
- ,}
?>
</body>
Eaglc', Web Development Using ,PHP
</html>
Output:
Dave Punk
mob: 5689741523
email: [email protected]
Monty Smith
mob' : 2584369721 , '
.
email: [email protected]
John Flinch
mob: 9875147536
email: [email protected]
• 2.11. STRINGS
Strings can be seen as a stream of characters. For example, ,'E' is a character and 'Eagle
Prakashan' is a string. There are two ways of creating strings in PHP :
1. Single-quote strings: This type of strings does not process Specialcharacters inside quotes.
<!DOCTYPE html>
<html>
<body>
<?php
/ / single-quote strings
$site = 'Welcome to Eagle Prakashan';
echo $site;
?>
</body>
</html>
Output:
Welcome to Eagle Prakashan
The above program compiles correctly. We have created a string, 'Welcome to Eagle
Praka&han'.and stored it in variable and printing it using echo statement. Let us now look at
the below program :
<htrnl>
<body>
<?php
/ / single-quote strings
PHP
$site =
'Eagle Prakashan';
echo 'Welcome to $site';
?>
</body>
</html> .t\
Output:
Welcome to $site
II
In the above program the echo statement prints the variable name rather than printing the
contents of the variables. This is because, single-quotes strings in PHP does not process special
characters. Hence, the string is unable to identify the '$' sign as start of a~variable name.
2. Double-quote strings: Unlike single-quotestrings, double-quotestrings in PHP is capable
of processing special characters.
<!DOCTYPE html>
<htrnl>
<body>
<?php
II double-quote strings
echo "Welcome to Eagle Prakashan<br>";
$site = "XML with PHP";
echo "Welcome to $site";
?>
</body>
</html>
Output:
Welcome to Eagle Prakashan
Welcome to XML with PHP
In the above program we can see that the double-quote strings is processing the special
characters according to their properties. Also, instead of the variable name $site, "XML with
PHP" 'is printed. . .
PHP treats everything inside double quotes (" ") as strings. Strings do not have any fix
limits or ranges. It can extend to any length as long as it is within the quotes.
Some of the important and frequently used special characters that are used with double-
quoted strings are explained below : .
• The characters beginning with a backslash("\") are treated as escape sequences and are
replaced with special characters. Here are few important escape sequences.
1. "\n" is replaced by a new line
2. "\t" is replaced by a tab space
Eagle's Web Development Using PHP
hebrevcO Converts Hebrew text to visual text and new lines (\n) into
<br>.
hex2binO Converts a string of hexadecimal values to ASCII characters.
html_ entity _decoder) Converts HTML entities to characters.
htmlentities/) Converts characters to HTML entities.
htmlspecialchars _decoder) Converts some predefmed HTML entities to characters.
htmlspecialcharst) Converts some predefmed characters to HTML entities.
implodet) Returns a string from the elements of an array.
joint) Alias of implodet).
Icfirsti) Converts the first character of a string to lowercase.
levenshteim) Returns the Levenshtein distance between two strings.
localeconvt) Returns locale numeric and monetary formatting information.
ltrimO Removes whitespace or other characters from the left side of a
string.
md50 Calculates the MD5 hash of a string.
md5_fileO Calculates the MD5 hash of a file.
metaphonet) Calculates the metaphone key of a string.
money _formatO Returns a string formatted as a currency string.
nlIanginfot) Returns specific local information.
nl2brO 'Inserts HTML line breaks in front of each newline in a string.
number _forman) Formats a number with grouped thousands,
ordt) Returns the ASCII value of the first character of a string.
parse_strO Parses a query string into variables.
prinu) Outputs one or more strings.
printft) Outputs a formatted string.
quoted _printable _decoder) Converts a quoted-printable string to an 8-bit string.
quoted _printable _encoder) Converts an 8-bit string to a quoted printable string.
quotemetat) Quotes meta characters.
rtrimO Removes whitespace or other characters from the right side of
a string.
setlocalet) Sets locale information.
shalt) Calculates the SHA-l hash of a string.
shal_fileO Calculates the SHA-l hash of a file.
similar _textO Calculates the similarity between two strings.
soundext) Calculates the. soundex key of a string.
sprintfO. Writes a formatted string to a variable.
sscanft) Parses input from a string according to a format.
str_getcsvO Parses a CSV string into an array.
str_ ireplacet) Replaces some characters in a string (case-insensitive).
3. str _replaceO function: This function takes three strings as arguments. The third argument
is the original string and the first argument is replaced by the second one. In other words, we
can say that it replaces all occurrences of the first argument in the original string by second
argument.
Example:
<7php
echo stueplace("Apple"[ "rnanqc", "I love Apple!"), '[<br>";
echo stueplace("Ishan", "Eagle Prakashan","Hello Ishanl"), "<br>";
7>
Output
I love mango!
Hello Eagle Prakashanl
4. strposO function : The strpost) 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
Example:
<?php
echo strpos("this is world of power!", "p"),
var_dump(strpos("Helio world!", "Peek"));
?>
Output
17
bool(false)
We can see in the above program, in the second example the string "Peek" is not present
in the first string, hence this function returns a boolean value false indicating that string is not
present.
s.trimO function : This function allows us to remove whitespaces or strings from both
sides of a string. Example :
<?php
echotrim("Helio Worldl", "Hedl");
7>
Output
lIoWorl
.. 2.12. FORMS
The Dynamic Websites provide the functionalitiesthat can use to store, update, retrieve and
delete the data in a database. A Form is a document that contains blank fields, that the user
Can fill the data or user can select the data. Casually the data will store in the database. We
can create and use HTML forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.
1. $_get method : Get request is the default form request. The data passed through get
request is visible on the URL browser so it is not secured. You can send limited amount of
data through get request. Below is the example to explain the concept :
(i) Create a new folder named "xml n php" in "htdocs folder" so as to maintain your
personalized files.
(ii) Write the following code in the notepad file and. save it as "form.html".
(iii) Again, write the following code in the notepad file and save it as "welcome.php".
- 0 x
<?php
$name=$ .....:GET["nall,1elt];llreceivingname field value in $name variable
echo "Welcome, Sname";
?>
Fig. 2.27. Code to create a php file.
(iv) The PHP file will take the data from HTML form file and show the output. To
check the output go to ... http://localhost/xml n php/form.html, the following Window
will be seen :_._ . ._
r:'0-~~~'-"""-""-"0,""':'~::':':l
Name: Eagle Prakashan i:~:visit(,I
•••••••••••••••••••
_.H••••H...._ J
••••
(v) Click "visit" button to see the PHP file as shown below
2. $:_POstMethod : Post request is widely used to submit form that have large amount of
data such as file upload, image upload, login form, registration form etc. The data passed through
post request is not visible on the URL browser so it is secured. You can send large amount of
data through post request. Below is the example to explain the concept :
(i) Create a new folder named "xml n php" in "htdocs folder" so as to maintain your
personalized files.
(ii) Write the following code in the notepad file and save it as "post eg.html",
<form action="login.php"method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
Fig. 2.30. Code to create a form.
PHP
(iii) Again, write the following code in the notepad file and save it as "post_eg.php".
- 0 X'
<?php·
$name=$_POST["name"];llreceiving name field value in $name variable
$password=$_POST["password"];llreceiving password field value in
Spassword variable
(iv) The PHP file will take the data from HTML form file and show the output. To check
the output go to - http://localhost/xml n php/post_eg.html, the following Window will
be seen:
Name: eagle
Password: I ••••••••••
L _._._. _.._ . . ...l
(v) Click "login" button to see the PHP file as shown below:
--;';~-c--4~iiejijfiji.+r;T:5~-;i+:j~;iji\i'~i~pjf~'::iiiJi~~t~m[1i]iia:'~r:fij~iliW.f~
Hi "'" • -"oJ.", of the user thus
.. 2.13. FUNCTIONS
A junction is a block of code written in a program to perform some specific task. PHP
function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP. The real power of PHP
comes from its functions. PHP has more than 1000 built-in functions and in addition you can
Eagle's Web Development Using PHP
create your own custom functions. A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
PHP provides us with two major types of functions :
1. Built-in functions : PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in the form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopenr), printrt), gettypet) and so
on.
2. User defined functions : Apart from the built-in functions, PHP allows us to create
our own customized functions called the user-defined functions. Using this we can create our
own packages of code and use it wherever necessary by simply calling it.
Why should we use functions ?
1. Reusability : If we have a common code that we would like to use at various parts of
a program, we can simply contain it within a function and call it whenever required. This reduces
the time and effort of repetition of a single code. This can be done both within a program and
also by importing the PHP file, containing the function, in some other program.
2. Easier error detection : Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
3. Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the change
will be reflected everywhere, where the function is called. Hence, easy to maintain.
III 2.13.1. Creating a Function
While creating a user defmed function we need to keep few things in mind :
1. Any name ending with an open and closed parenthesis is a function.
2. A function name always begins with the keyword function.
3. To .call a function we just need to write its name followed by the parenthesis.
4. A function name cannot start with a number. It can start with an alphabet or underscore.
5. A function name is not case-sensitive.
Syntax:
function function_nameO
{
executabl code;
Example
<?php
func:tlcmfuncEagleO
{
ec::ho"Thls is Eagl@ Prakashan";
PHP
?>
Output
This is Eagle Prakashan
Example:
<html>
<body>
<?php
Output
The product is 30.
<?php
Output:
Ram is 15 years old
Adam is 12 years old
In the above example, the parameter $num has a default value 12, if we do not pass any
value for this parameter in a function call then this default value 12 will be considered. Also,
the parameter $str has no default value, so it is compulsory.
<?php
?>
</body>
</html>
Output' :
The product is 30.
<?php
Eagle's, Web Development Using PHP
II pass by value
function by_val($num) {
$num += 2;
return $num;
II pass by reference
function by_ref(&$num) {
$num += 10;
return $num;
$n = 10;
by_val($n);
echo "The original value is still $n <br>":
by_ref($n);
echo "The original value changes to $n";
7>
</body>
</html>
Output:
The original value is still 10
The original value changesto 20
The Fig. 2.34 below explains the concept and working of cookies.
need to know who we are but offer us the ability to "remember me" when you enter username
and password.
For example : Gmail.
3. Third-party cookies : Third party cookies are the cookies being set with the different
domain than the one shown in the address bar. For example, if you were to visit
Sendflowers.com, it may set the cookie for the address of SomeAdvertiser.com. Later, when
you visit RebuidEngines.comit may set the cookie for SomeAdvertiser.com.Both of these cookies
will be used by SomeAdvertiser.com to ascertain that you are a person who sends flowers and
works on cars. These are used by advertising agencies who have clients that pay for displaying
ads for products and services but don't want to waste money displaying them to people who
aren't going to be a customer.
4. 'HTTP cookies : When you send a request to the server, the server sends a reply in
which it embeds the cookie which serves as an identifier to identify 'the user. So, next time
when you visit the same website, the cookie lets the server know that you are visiting the website
again.
• 2.14.3.PHP cookie
PHP cookie is a small piece of information with the maximum size of 4 KB which is stored
at client browser. It is used to recognize the user. They are typically used for keeping track of
information such as a usemame that the site can retrieve to personalize the page when the user
visits the website next time. Cookies are usually set in an HTTP header but JavaScript can also
set a cookie directly on a browser. Cookie is created at server side and saved to client browser.
Each time when client sends request to the server, cookie is embedded with request. Such way,
cookie can be received at the server side. In short, cookie can be created, sent and received at
server end.
The concept is shown below in Fig. 2.35.
3, Request + Cookie
1, Request
2. Response + Cookie
Browser
Parameters : The setcookieO function requires six arguments in general which are
1. Name: It is used to set the name of the cookie.
2. Value: It is used to set the value of the cookie.
PHP
3. Expire : It is used to set the expiry timestamp of the cookie after which the cookie
can't be accessed.
4. Path: It is used to specify the path on the server for which the cookie will be available.
5. Domain : It is used to specify the domain for which the cookie is available.
6. Security : It is used to indicate that the cookie should be sent only if a secure HTTPS
connection exists.
Below are some operations that can be performed on cookies in PHP
Creating cookies: Creating a cookie named "user" and assigning the value "John Doe" to
. it. The cookie will expire after 30 days (1 day * 24 hours * 60 mins * 60 seconds).
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, timeO +
(86400 * 30), "!"); II 86400 = 1 day
?>
<htrnl>
The code above will not give any output, but a cookie will be stored. To see the cookie
go to "developers tool" in your browser as shown below in Fig. 2.36.
Newlab X
Newtab Cul+T
New window Cld+N
Newincognilowindow Ctrl+Shift+N
History
. Downloads Ct.t+.J
•
Bookmarl:s ,.
Print.. Ctrl+P
Cast...
..
Then, go to Application - Cookies - Select "Localhost" , there you will find the cookie
you created. The steps are explained in the Fig. 2.37 below.
<!DOCTYPE html>
<?php
$cookie _name = "user'" ,
$cookie_value = "Eagle Prakashan";
setcookie($cookie_name, Scookie value, timet) + (86400 * 30), "I"); II 86400 = 1 day
?>
f:htm1>
<body>
PHP
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Sorry not recognized!";
} else {
echo "Hello '" . $cookie_name . '" !<br>";
echo "Yourname is: " . $_COOKJE[$cookie_name]."<br>";
echo "your account is valid for 30 days";
}
?>
</body>
<lhtml>
Fig. 2.38.Code to access or use the cookie using PHP.
Hello' user' !
Your name is: Eagle Prakashan
your account is valid for 30 days
Fig. 2.39. Output of the cookie accessed.
To delete a cookie, use the setcookieOfunction with an expiration date in the past as shown
in the code below.
11.-;,......,· Not.....
fije Edit Fot'tnIIt Yiew Help
~?php
II set the expiration date to one hour ago
setcookie("user", "", timet) - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
<lhtml>
Fig. 2.40. Code to delete the cookie.
- The output of the above code on "Localhost" is
Eagle's Web Development Using PHP
a resource
In this model, if you wanted to display user-specific information, you'd have to authenticate
a user in each request. Imagine if you had to type your username and password on every page
that displayed your profile information! Yes, it would be cumbersome and not practical at all,
and that's where sessions come into the picture. A session allows you to share information across
the different pages of a single site or app - thus it helps maintain state. This lets the server
know that all requests originate from the same user, thus allowing the site to display user-specific
information and preferences.
PHP
Let's quickly go through a common login flow for a website to understand what happens
behind the scenes.
1. A user opens the login page of a website.
-
2. After submitting the login form, a server on the other end authenticates the request by
validating the credentials that were entered.
3. If the credentials entered by the user are valid, the server creates a new session. The
server generates a unique random number, which is called a session id. It also creates a
new file on the server which is used to store the session-specificinformation.
4. Next, a session id is passed back to the user, along with whatever resource was requested.
Behind the scenes, this session id is sent in the PHPSESSID cookie in the response
header.
5. When the browser receives the response from the server, it comes across the PHPSESSID
cookie header. If cookies are allowed by the browser, it will save this PHPSESSID
cookie, which stores the session id passed by the server.
6. For subsequent requests, the PHPSESSID cookie is passed back to the server. When the
server comes across the PHPSESSID cookie, it will try to initialize a session with that
session id. It does so by loading the session file which was created earlier during session
initialization. It will then initialize the super-global array variable $_SESSION with the
data stored in the session file.
In this way, the user data is preserved across multiple requests and the user is kept logged
in throughout a session.
The following diagram depicts how the HTTP protocol works with sessions.
Requests a resource
Session variables are stored in associative array called $_SESSIOND. These variables can be
accessed during lifetime of a session. Create a file with the name "session _start. php" as shown
below in Fig. 2.44.
5!~.~$~.Nt;~
'* too ~ V>tw }ffi~
<?php
If Start the session
session jstartt);
'?>
<!DOCTYPE html>
<html>
<body>
<!php
/1 Set session variables
$_SESSION["fav _publisher"] """Eagle Prakashan";
$_SESSION["fav_subject"j;· "PHP";
echo "Welcome I to session class <br> All Session variables are set.";
?>
</body>
<lhtml>
m_+_"' ..
<?php
session_startO;
?>
<!DOCTYPE html>
<html>
<body>
<?php
if( isset( $_ SESSION['counter'] ) ) {
$_ SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
</body>
<lhtmI>
·····,.····················.·························
,_'.
11 P Type here to search
':"",::"'' ' ,:< ,;
Fig. 2.46. Code to retrieve the session variables and use of counter.
-G --.-'1 _.
Youhave visited this page 3time in this
.
session,
My favorite Publisher is Eagle Prakashan.
And my favorite subject is PHP.
Fig. 2.47. Output of the code above.
Eagle's Web Development Using PHP
• 2.15.3.Timeout in sessions
In PHP, sessions are maintainedto check if the user is active. When the user becomes inactive
and the user forgets to logout from the web page, there is a chance of other users viewing the
page causing security breach. By default, a session in PHP gets destroyed when the browser is
closed. Session timeout can be customized, to make the user's page inactive after a fixed time.
Below example shows how to customize the session :
1. Make a folder in "htdocs" with the name "session timeout".
2. Write the following code in the notepad file and save it with the name "login.php".
., login - Notepad
File Edit Format View Help
<?php ..
session_ start();
?>
<hOO!>
<form name="forml" method="post">
<table>
<tr>
<td>Usemame<ltd>
<td><input type="text" name="text"><ltd>
<Itt>
<tr>
<td>Password<ltd>
<td><input type="password" name="pwd"><ltd>
<ltr>
<tr>
.<td><input type="submit" value="SignIn" name="login"><ftd>
<ns> .
<ltable>
<lform>
<!bOO1>
<?php
if (isset( $_POST['login']))
{
$v1 = S_POST['text'};
$v2 = .$_POST[,pwd1;
$_SESSION['IUSetJ] = $vl;
$_ SESSION['start.'] = time(); II Taking now logged in time.
$_SESSION['expire'] = $_SESSION[,staIt'] + (1 * 60);
II Ending a session in 1 minutes from the starting time,1
header("Location: homepage.php");
}
else { echo "Please enter the usemame or password again!"; }
1>
Fig. 2.48. Logln.php.
PHP
Here; the HTML code is used to make a form. In the PHP code, isseu) function is used to
check if the user has clicked on the "Signln" button. Also, to check ifthe user has filled the
user name and password. If all the entries are filled, then the session variables will be
initiated. "$_SESSION['luser,]" variable will get the user name to pass the value to other
PHP page. "$_SESSION['start']" variable is set to save the login time of the user.
"$_SESSION['expire']" variable is used to timeout the user after 1 minute. "header(" Location:
homepage.php");" this will redirect the user to next page "homepage.php" of the website.
The output of the above code is
Password .....
3. Write the code below in notepad and save the file as "homepage.php".
11 homepage- Notepad
r:iPhp - _.
File Edit Format View Help
session start();
if (!isset($ _SESSION['lusel J]))
(
echo "Please Login again";
echo '<a href="login.php">Click Here to Login<la>';
else
Snow = time(); /1 Checking the time now when home page starts.
if ($now > $_SESSION['expire'])
{
session_ destroy();
echo 'YOlU' session has expired! <a href-="login.php">Login here-oa>';
}
else
{ IIStarting this else one [elsel]
?>
<!-- From here all HTML coding can be done -->
<html>
Welcome
<?php
echo $_SESSION['lusel'];
echo '<a href="logout.php">Log cut-e/a>';
?>
<zhtml>'
<?php
}
.}
?>
Fig. 2.50. homepage.php.
Eagle's Web Development Using PHP
The "session startt);" code continues the session. The "if (!isset($_SESSION['luser']))"
implies if the user is not set, then this page will redirect the user to "login.php" page
again. The else part checks if the 1 minute has passed without any event done by the
user then, the session will get expired. The "sessiondestroyt);" function is used to
destroy the session. This function does not need any argument and a single call can
destroy all the session variables. If you want to destroy a single session variable then
you can use unseti) function to unset a session variable. When the user clicks on the
"Signln" button of the "login.php" page, then this "homepage.php" will show the
"Welcome" output to the user as shown below:
... ) 0
rn~ .~~~H.
Q
.' Ci (!l
ni~.·~\Qtil!1
<?php
session _starn);
session _ destroyt);
echo '<a href="login.php">Click Here to Login</a>';
?:1
Fig. 2.53. logout.php.
Here, session has been destroyed and the user has been given a link to login again i.e. to
go to "login.php". The output of this code is shown below
Ii-
mhm~ .~$W ..... ~...._.",.,.,.,.,.~w_ ...., ......
• Q.3~"What is a string ?
~"i Strings can be seen as a stream of characters.
; Q.4~.1What are built-in functions ?
\:.~jl These functions are already coded ,and store.d in the form of functio~. To use those we just'
: !need to call them as per our requirement like, var_dump, fopenO. print jf), gettypet) and so
on.
Who can access a cookie ?
Only the same website that saves information to a cookie can access' it.
hello world!!!
(il) Multi-line or Multiple line comment : These are used to accommodate multiple lines
with a single tag and can be extended to many lines as required by the user. To add this, we
need to begin and end the line with (1* ... */). For example :
<?php
This is a multi line comment
In PHP variables are written
by adding a $ sign at the beginning.*1
$eagle= "hello children!";
echo$eagle;
The PHP break keyword is used to terminate continue keyword is used to halt
the execution of a loop prematurely. the current iteration of a loop but it does
not terminate the loop.
The break statement is situated inside the
statement block. It gives you full control and Just like the break statement the continue
whenever you want to exit from the loop you statement is situated inside the statement block
can come out. After coming out of a loop containing the code that the loop executes,
immediate statement to the loop will be preceded by a conditional test. For the pass
encountering continue statement, rest of the
executed. loop code is skipped and next pass starts.
Loop
False False
•• Objective Questions ••
~ Fill in the blanks ~
1. PHP was started out as a small .......... project.
2. PHP is scripting language.
3. A variable starts with the , followed by the of the variable.
4. arrays are such arrays which store another array at each index instead of single element.
•• Review Q"estions ••
1. Explain syntax of PHP.
2. What is a data type ? Explain various data types of PHP.
3. Explain the new operators introduced in PHP7.
4. What is an array ? Explain various types of arrays in PHP.
5. What is the difference between single-quote strings and double-quote strings ?
6. Differentiate between $_get and $_post method.
7. Explain functions and function with parameters.
8. Differentiate between parameter passing to function by value and by reference in PHP.
9. Explain how the server stores and use cookies information.
10. What is a session ? How to start, maintain and destroy the session in PHP ?
11. What is CMS ? Explain in detail.
,.
..
v