0% found this document useful (0 votes)
52 views83 pages

Colour

- XML Basics document provides questions to test understanding of XML fundamentals including XML document anatomy, declarations, elements, attributes, components, and differences between XML and HTML. - Questions cover XML declaration, attributes versus elements, empty elements, XML document components, and differentiating XML from HTML.

Uploaded by

mandeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views83 pages

Colour

- XML Basics document provides questions to test understanding of XML fundamentals including XML document anatomy, declarations, elements, attributes, components, and differences between XML and HTML. - Questions cover XML declaration, attributes versus elements, empty elements, XML document components, and differentiating XML from HTML.

Uploaded by

mandeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

·

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

Hello, today is Friday, August 21st, 2020.


Fig. 2.2. Output.

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 .

., 2.1. FEATURES OF PHP


The various features of PHP are as the following
1. PHP is open source and free, thus, one can freely download, install and start developing/
using it.
2. PHP has a very simple and easy to understand syntax, hence the learning curve is smaller
as compared to other scripting languages like JSP, ASP etc.
Eagle's Web Development Using PHP

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.

Fig. 2.4. PHP is cross-platform.


4. All the popular web hosting services support PHP. Also, the web hosting plans for PHP
are generally the amongst the cheapest plans because of its popularity.
5. Popular content management systems like Joomla, Drupal etc. are developed in PHP
and if you want to start your own website like Studytonight, you can easily do that
with PHP.
6. With PHP, you can create static and dynamic webpages, perform me handling operations,
send E-mails, access and modify browser cookies, and almost everything else that you
might want to implement in your web project.

Passed straight
Static web page to browser Browser
(.htm or .html)

Dynamic web page Browser


(.php or .asp)

Server processes scripting language,


querying database and other functions
then passes resulting html page to browser
Fig. 2.5. Static and dynamic web pages.
7. PHP is fast as compared to other scripting languages like JSP and ASP.
8. PHP has in-built support for MySQI.:.,which is one of the most widely used database
management system.
PHP

.. 2.2. APPLICATIONS OF PHP


Some important applications of PHP are as the following :
1. It can be used to create Web applications like Social Networks (Facebook, Digg), Blogs
(Wordpress, Joomla), eCommerce websites (OpenCart, Magento etc.) etc.
2. Command Line Scripting. You can write PHP scripts to perform different operations
on any machine, all you need is a PHP parser for this.
3. Create Faceboek applications and easily integrate Facebook plugins in your website,
using Facebook's PHP SDK.
4. Sending E-mails or building E-mail applications because PHP provides with a robust
E-mail sending function.

.. 2.3. INSTALLATION OF PHP


InstallingPHP on your developmentPC allows you to safely create and test a web application
without affecting the data or systems on your live website. There are some excellent all-in-one
Windows distributions that contain Apache, PHP, MySQL and other applications in a single
installation file, e.g. XAMPP, WampServer, MAMP etc. However, one can install Apache and
PHP manually to learn more about the system and its configuration options.
Here, we will install XAMPP Lite to work on PHP.
1. XAMPP is the most popular PHP development environment. It is cross-platform and
open source. With its help a local server environment on Windows PC can be setup. It
also helps user's to setup Apache server and MySQL server in Windows 10. You need
to install this free software on your Windows 10 PC first to work on PHP. Make sure
to download the latest version of XAMPP for Windows. Launch the installer and follow
on-screen tips to install XAMPP on your Windows PC.
IISetup x

.....•.

...-.,~.
,

Fig. 2.6. Install XAMPP.


Eagle's Web Development Using PHP

2. After installation, start XAMPP control panel and run Apache and MySQL as shown in
Fig. 2.7.

iii XAM?P Control Panelv323 ICompiled: Mar 7th 2019 J o x


001$'01Panel vU.3

PM [main} Checking fur prerequisites


Pr..~ [main) All prefeq!Jisit~ found
PM [main) Initlafizing ModIJles
PM [mysqlJ 1J\MW MySQL is already running Oil port 3306
PM (main) Starting Check-Timer
5:05<.04PM [mainl CootrolPanel Ready
5:1)5:11PM [Apache) Attempting to start Apache SAl•..
5:U5:12 PM (Apach~l Status change detect.e« running

Fig. 2.7. Run XAMPP control panel.

Check if the server is running by opening the ''http://localhostldashboard/'' in the browser


as shown below in Fig. 2.8.

Welcome to XAMPP for Windows 7.3.5

~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

Fig. 2.8. Localhost Is In operation.


PHP
3. To run a PHP file, open "XAMPP" folder in C:\ drive and then, go to "htdocs" folder
("C:\xampp\htdocs"). Open a notepad file - write the code as shown below in Fig. 2.9.
II! !New Text Document - Notepad
File Edit. Format View Help
<tDOCTYPE html>
<hOOl>
<body>

<?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

Fig. 2.10. Save as the file with .php extension.


5. Run the created file in "localhost" by writing http://localhostlmy_frrst_code.phpand
the output is shown below in Fig. 2.11.

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.

• 2.4. SYNTAX OF PHP


PHP files are saved with ".php" extension. PHP scripts can be written anywhere in the
document within PHP tags along with normal HTML.
• 2.4.1. PHP Tags or Escaping To PHP
The PHP parsing engine needs a way to differentiate PHP code from other elements in the
page. The mechanism for doing so is known as 'escaping to PHP'. There are various ways in
which this can be done. Few methods are already set by default but in order to use few others
like Short-open or ASP-style tags we need to change the configuration of php.ini file. These
tags are also used for embedding PHP within HTML. There are four such tags available for
this purpose :
1. Canonical PHP tags : The script starts with < ?php and ends with ? >. These tags are
also called 'Canonical PHP tags'. Every PHP command ends with a semi-colon(;). For example:
<?php
# Here echocommand is used to print
echo "Hello, world!";
?>
Output
Hello, world!

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!

• 2.4.3. PHP is whitespace Insensitive


Whitespace is the stuff you type that is typically invisible on the screen, including spaces,
tabs and carriage returns (end-of-linecharacters). PHP whitespace insensitive means that it almost
never matters how many whitespace characters you have in a row. One whitespace character is
the same as many such characters. For example, each of the following PHP statements that
assigns the sum of 2 + 2 to the variable $fourl and $four2 is equivalent _
<!DOCTYPE html>
<htrnl>
<body>
<7php
$fourl = 2 + 2; II single spaces
$four2 =
2+
2;11 multiple lines
echo "$fourl and $four2"
7>
</body>
</html>
Output:
4 and 4

• 2.4.4. PHP is case-sensitive


All the keywords, functions and class names in PHP (while, if, echo etc.) are NOT case-
'sensitiveexcept variables. Only variables with different cases are treated differently. Let's look at
this example :
<!DOCTYPE html>
<htrnl>
<body>
<7php
II Here we can see that all echo
II statements are executed in the same manner
$variable = 25;
echo $variable;
ECHO $variable;
PHP
EcHo $variable;
II but this line will show RUNTIME ERRORas
II "Undefined Variable"
echo $VARIABLE
?>

</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•

• 2.4.5. Braces make blocks


In PHP, statements can be put in a sequence by enclosing them in a set of curly braces. In
the example below both statements are equivalent -
if(3==2+1)
print("Good - I haven't totally lost my rnlnd.cbr>"):

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.

Integers These are whole numbers, <IDOCTYPE html>


without a decimal point, like <html>
4195.
<body>
<?php
$x = 5;
$y ;;; 4;
echo $x .r $y;
7>
</body>
. </html>
Output:
9
Doubles These are floating-point numbers, <! DOCTYPE html>
like 3.14159 or 49.1. <html>
<body>

, <?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

Booleans They have only two possible <!DOCTVPE html>


values either true or false. <html>
<body>
<?php
$width=!50; //not 50
if ($width :: 0) =
{
var_dump ($width);
echo "The width needs to be a
non-zero number":

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

NULL It is a special type that only has <!DOCTYPE html>


one value : NULL. A variable of . <html>
data type NULL is a variable <body:>
that has no value assigned to it. <?php
If a variable is created without a
$x = "Hello world!";
value, it is automatically assigned
$x = null;
a value of NULL. Variables can
var_dump{$x);
also be emptied. by setting the
value to NULL. ?>
</body>
</html>
Output:
NULL

Strings These contain sequences of <!DOCTYPE htrnl>


characters, like 'PHP supports <html>
string operations.' <body>
<?php
$txt = "Eagle Prakashan";
echo "I love $txt!";
?>
</body>
</html>
Output:
I love Eagle Prakashan!

Arrays They are named and indexed Example 1 :


collections of other values. <!DOCTYPE html>
<htrnl>
<body>
<?php
Scars = array{"Volvo", "BMW",
"Toyota");
echo Scars;
?>
</body>
</html>
Output:
Array
. ,.
It is the data type of the variable
$cars.
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.

~ Objects These are instances ' of <!DOCTVPE html>


programmer-defined classes. <htrnl>
§o which can package up both other
<body>
s-o kinds of values and functions that
are specific to the class.
U <?php
class Car{
function CarO {
$this - model = "VW";

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 :

Fig. 2.13. Scope of variables in PHP.

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;

II using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html>

Output:

Variable x inside function is: 5

Notice: Undefined variable: x in


C:\xampp\htdocs\xmlphp\localvar.pbp on line 13

Variable x outside function is:

Fig. 2.14. Output of the code.

Here, the variable $x is visible in function "myTest".


Local variables will be destroyed once the end of the code block is reached. Hence, the
same named variables can be declared within different local scopes.
Eagle's Web Development Using PHP

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();

echo "<p>Variable x outside function is: $x</p>";


?>
</body>
</html>

Output:

Notice: Undefined variable: x in


C:\xampp\htdocs\xmlpbp\localvar.php on line 10

Variable x inside function is:

Variable x outside function is: 5

I:i - - U'

Fig. 2.15. Output 0' the oode above.


PHP
PHP global variables can be defmed by using global keyword. If we want to use global
variables inside a function, we have to prefix the global keyword with the variable. The following
code shows a code block to learn how to use the global keyword with a PHP variable to declare
it as a global variable.
<!DOCTYPE html>
<htrnl>
<body>

<?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;

echo "<p>Variable x outside function is: $x</p>";


?>

</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.

." 2.6. STATEMENTS


A statement in PHP is any expression that is followed by a semicolon (;). Any sequence of
valid PHP statements that is enclosed by the PHP tags is a valid PHP program. The example
PHP _

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

. Table 2.2. Arithmetic operators.

Subtraction Differences the operands.


.Multiplication $x * $y . Product of the operands.
/ Division $x I $y Quotient of the operands.
** Exponentiation $x ** $y $x raised to the power $y.
% Modulus $x % $y ·Remainoerof the operands.

$pte: The exponentiation has been introduced in PHP 5.6.

Example:
<!DOCTYPE html>
<html>
<body>

<?php
il variable 1
$x =
29;
II variable 2
$y = 4;

II some arithmetic operations on


II these two variables
echo ($x + $y), "< br>";
echo($x - $y), "< br>":
echo($x * $y), "< br>";
echo($x I $y), "< br>";
echb($x % $y), "< br>";
?>

</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 :.

Table 2.3. Logical or Relational operators.

True if both the operands are true else false.


or Logical OR . $:x or $y True if either of the operand is. true .else false ..
xor Logical XOR $x xor $)' True if either of the operand is true and false
if both are true.
&& Logical AND $x && $y True if both the operands are true else false.

II Logical OR $x I $y True if either of the operand is true else false.


Logical NOT !$x True if $x is false.

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.

-- Equal to $x == $y Returns True if both the operands are equal.


!= Not equal to $x != $y Returns True if both the operands are not equal.
<> Not equal to $x < > $y Returns True if both the operands are unequal.
--- Identical $x === $y Returns True if both the operands are equal and
are of the same type.
!== Not identical $x == $y Returns True if both the operands are unequal
and are of different types.
< Less than $x < $y Returns True if $x is less than $y.
> Greater than $x > $y Returns True if $x is greater than $y.
<= Less than or $x < = $y Returns True if $x is less than or equal to $y.
equal to
>= Greater than $x > = $y Returns True if $x is greater than or equal to $y.
or equal to
<=> Spaceship $x< =>$y Returns an integer less than, equal to, or greater
than zero, depending on if $x is less than, equal
to, or greater than $y. Introduced in PHP 7.

Example:
<!DOCTYPE htrnl»
<html>
<body>

<?php
$a = 80;
$b = 50;
$c = "80";
displays structured information such as type and value of the given variable. */

var_durllp($a == $c); echo "<br>":


"

-
/*The var_dumpO function is used to dump information about a variable. This function

var_dump($a != $b) ; echo "<br>":


var_dump($a < > $b) ; echo" <br>":
var_dump($a ===
$c) ; echo "<br>":
var_dump($a !== $c) ; echo "<br>":
var_dump($a < $b) ; echo "<br>":
$' var_dump($a > $b) ; echo "<br>":
'I•• var_dump($a <= $b) ; echo "<br>":
var_dump($a >= $b);echo "<br>":

$x =5;
$y :;: 1Q;

Elcho ($x <:;;: > $y); / / returns - 1 because $x is less than $y


echo "<br>";
$x = 10;
$y :::::10;
echo ($)( <;:;:;> $y); II returns 0 because values are equal
echo "<br>":
sx =: 15;
$y :::: 10;
echo ($x <: =::> $y); II returns + 1 because $x is greater than $y
7>
</body>
</htrnl>
Output :
beelttrue)
bool(true)
bool(true)
bool(false)
beelttrue)
bool(false)
bool(true)
bool(false)
boelrtrue)
= 1
o
1
- 4. Conditional or Ternary operators
Eegle's Web Development

These operators are used to compare two values


and take either of the result simultaneously, depending on whether the outcome is TRUE or
FALSE. Table 2.5 shows the ternary operators, that PHP provides us.
Using PHP

Table 2.S. Ternary operator;

?: Ternary $x = exprl ? expr2 : . Returns the value of $x.


expr3 .
The value of $x is expr2 if exprl =
TRUE.
The value Of $x is expr3 if exprl =
FALSE

n Null $x = exprl ?? expr2 Returns the value of $x.


coalescing The value of $x is
exprl if exprl exists and is not NULL.
If exprl does not exist, or is NULL, the
value of $x is expr2.
Introduced in PHP 7

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

II subtract then assign operator


$y =
70;
$y -= 10;
echo $y, "<br>":
II multiply then assign operator
$y = 30;
$y *= 20;
echo $y, <br> ";
II

II Divide then assign (quotient) operator


$y = 100;
$y /= 5;
echo $y, <br>":
II
! •
- II Divide then assign (remainder) operator
$y = 50;
$y %= 5;
Eagle's Web Development Using PHP

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.

+ Union $x + $y Union of both i.e., $x and $y.


Equality $x == $y Returns true if both have same key-value pair.
!= Inequality $x != $y Returns true if both are unequal.
Identity $x === $y Retums true if both have same key-value pair
in the same order and of same type.
,__ Non- identity $x !== $y Returns true if both are not identical to each
other.
<> Inequality $x < > $y Returns true if both are unequal.

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.

++ Pre-increment ++$x First increments $x by one, then return $x.


Pre-decrement _$x First decrements $x by one, then return $x.
++ Post -increment $x++ First returns $x, then increment it by one.
Post-decrement $x- First returns $x, then decrement it by one.

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.

Concatenation $x.$y Concatenated $x and $y.


= Concatenation and assignment $x.=$y Appends $y to $x.

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!!!

... 2.8. DECISION MAKING STATEMENTS


i ,
' PHP conditional statements allow you to make a decision, based upon the result of a'
condition. These statements are called as Decision Making Statements or Conditional, Statements.
It's just like a two-way path. If you want 'something then go this w~y or else tum'
that way.
To use this feature, PHP provides us with four conditional statements ~:
1. if statement
2. if...else statement
3. if., .elseif.. .else statement
4. switch statement.
,
1. If statement : This statement allows' us to set a condition. On qeing TRUE" the following
block of code enclosed within the, if clause will be executed as shown: in the flowchart below :

False

Fig. 2.18. Concept of If at.tement.


Syntax :
if (condition){
II if TRUE then execute this code

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

Fig. 2.17. Concept of If.. lae atatement.


Syntax :
if (condition) {
II if TRUE then execute this code

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.

3. if•••elseif•.•else statement : This allows us to use multiple if...else statements.This statement


is used when there are multiple conditions of TRUE cases. The flowchart shows the concept:

Fig. 2.18. Concept of If-else-If statement.


Syntax :
if (condition) {
// if TRUEthen execute this code

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.

Fig. 2.18. Concept of switch .tat.ment.


-'.,

switCh(n) .I ,
case statemenn: , ,
code to be executed if n==statementl;
break;
case statement2:
, .' code to b~executed if 'n= =statement2;
, .'
k ' ,
'brea''"

, case' statements: ' ' .'


'. code to ,be executed if n;:=statement3; ,
break;
case statement4:
code to be executed if n= =statement4;
break;

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',· ~,

echo'~Its'Fe~ru~ry"; ,', ) '. -1<1 ",

. 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.

Fig. 2.20. Concept of for loop.


Syntax :
for (initialization expression; test condition; update expression)
{
II code to be executed

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

Fig. 2.21. Concept of while loop.


Syntax :
while (if the condition is true) {
II code is executed

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. . .

Fig; 2.22; concept of ci07whlle loop.


Syntax :
. do {
Ilcode is executed
} while (if condition is true);
Example:
<?php

II PHPcode to illustrate do...while loops


$num= 2;
dot
. $num+= 2;
echo$num, ''\n";
} while($num< 12);

?>
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

Fig. 2.23. Concept of foreach loop.

,
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"
};

II Loop through employee array


foreach($employeeas$key= > $element) {
echo$key. ";". $element. "< br» ";

?>

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 '.. .

I/One way to create an indexed array


$name_one= array("Zack", "Anthony", "Ram", "Salim", "Raghav");

II Accessing the elements directly


echo"Accessing the 1st array elements directly:\n";
echo$name_one[2], "\n";
echo$name_one[O], "\n";
echo$name_one[4], "\n";

.il Second w~y to create an. indexed array


$name..;two[O] = "ZACK";
. ~name_two[11 ::: "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SAliM"; . ' ;.
$name_two[41 _ "RAGHAV";

II Accessing the elements directly


echo"Accessing the 2nd array elements directly:\n";
echo$name_two[2], "\n";
echo$name_two[O], "\n";
echo$name_two[4], "\n";

.?>
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");

II One way of Looping through an array usign foreach


echo "Looping using foreach: cbr>":
foreach ($name_one as $val){
echo $val. "<br>";

II countO function is used to count


II the number of elements in an array
$round .. count($name_one);
echo "\nThe number of elements are $round <br>tI;
II Another way to loop through the array using for
echo "Looping using for: ebr>":
for($n .. 0; $n < $round; $n++){
echo $name=one[$n], "<br>";

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.

The Fig. 2.24 below explains the concept of associative array.

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);

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


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

1* Second method to create array, *1


$salaries['mohammad']="high";
$salaries['qadir']="medium";
$salaries['zara']="Iow";
echo "Salary of mohammad is ". $salaries['mohammad']."<br I>";
echo "Salary of qadir is ". $salaries['qadir'],"<br I>";
echo "Salary of zara is ". $salaries['zara']."<br I>":
?>

</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>"; ,

II Looping through an array using. for


echo "\nLooping using for: <br>":
$keys = array_keys($name_one);
$round = count($name_one);

for($i=O; $i < $round; ++$i) {


echo $keys[$il . ' , . $~a.me_one[$keys[$ill . "< 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

Looping using for:


Zack Zara
Anthony Any
Ram Rani
Salim Sara
Raghav Ravina

3. Multidimensional arrays : Multidimensionalarrays are such arrays which store an another


array at each index instead of single element. In other words, we can define multidimensional
arrays as array of arrays. As the name suggests, every element in this array can be an array
and they can also hold other sub-arrays within. Arrays or Sub-arrays in multidimensionalarrays
can be accessed using multiple dimensions.
Example:
<!DOCTVPE htrnl>
«html>
<body>

<?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

Traversing multidimensional arrays : We can traverse through the multidimensionalarray


using for and foreach loop in a nested way. That is, one for loop for the outer array and one
for loop for the inner array.
Example:
<!DOCTVPE html>
<html>
<body>

.<?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

3. "\$" is replaced by a dollar sign


4. "\r" is replaced by a carriage return
5. "\\" is replaced by a backslash
6. "\'''' is replaced by a double quote
7. "\ ", is replaced by a single quote
• The strings starting with a dollar sign ("$") are treated as variables and are replaced
with the content of the variables.
PHP string functions: The PHP string functions are part of the PHP core. No installation
is required to use these functions.
Table 2.10. Inbuilt string functions in PHP.

addcslashesO Returns a string with backslashes in front of the specified


characters.
addslashesO Returns a string with backslashes in front of predefined
characters.
bin2hexO Converts a string of ASCII characters to hexadecimal values.

chopt) Removes whitespace or other characters from the right end of


a string.
chn) Returns a character from a specified ASCII value.
chunk:_splitt) Splits a string into a series of smaller parts.
convert _cyr_stringt) Converts a string from one Cyrillic character-set to another.
convert _uudecodet) Decodes a uuencoded string.
convert_ uuencodet) Encodes a string using the uuencode algorithm.

count _charst) Returns information about characters used in a string.

crc320 Calculates a 32-bit CRC for a string.


cryptt) One-way string hashing.
echoO Outputs one or more strings.
exploder) Breaks a string into an array.
fprintf() Writes a formatted string to a specified output stream.
get_html_ translation _tablet) Returns the translation table used by htmlspecialcharsO and
htmlentitiest).
hebrevt) Converts Hebrew text to visual text.

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).

:str_padO Pads a string to a new length.


str_repeatO Repeats a string a specified number of times.
str replacer) Replaces some characters in a string (case-sensitive).

str_rot130 Performs the R0T13 encoding on a string.

str_shuffleO Randomly shuffles all characters in a string.


I str_spliu) Splits a string into an array.
str_word _ counn) Count the number of words in a string.
strcasecmpt) Compares two strings (case-insensitive).
strchrt) Finds the first occurrence of a string inside another string (alias
of strstrtj).
strcmpt) Compares two strings (case-sensitive).
·strcollO Compares two strings (locale based string comparison).

strcspnO Returns the number of characters found in a string before any


part of some specified characters are found.
·strip; tagsr)
stripcslashesO Unquotes a string quoted with addcslashest).

stripslashesO Unquotes a string quoted with addslashest),


stripost) Returns the position of the first occurrence of a string inside
another string (case-insensitive).
stristrl) Finds the first occurrence of a string inside another string (case-
insensitive).
strlenO Returns the length of a string.
, stmatcasecmpf) Compares two strings using a "natural order" algorithm (case-
insensitive).
· strnatcmpt) Compares two strings using a "natural order" algorithm (case-
sensitive) .
PHP

String comparison of the first- n characters (case-insensitive).


String comparison of the first n characters (case-sensitive):
Searches a string for any of a set of characters.
Returns the position of the first occurrence of a string inside
another string (case-sensitive).
strrchrt): Finds the last occurrence of a string inside another string.
strrev() Reverses a string.
strripos() Finds the position of the last occurrence of a string inside
another string (case-insensitive).
strrpost) Finds the position of the last occurrence of a string inside
another string (case-sensitive).
strspn() Returns the number of characters found in a string that contains
only characters from a specified charlist.
strstr() Finds the first occurrence of a string inside another string (case-
sensitive). .
strtokt) Splits a string into smaller strings.
strtolowert) Converts a string to lowercase letters.
strtouppert) Converts a string to uppercase letters.
strtrt) Translates certain characters in a string.
substrt) Returns a part of a string.
substr_comparet) Compares two strings from a specified start position (binary safe
and optionally case-sensitive). .
substr_counn) Counts the number of times a substring occurs in a string;
.substr_replace() Replaces a part of a string with another string.
trimt) Removes whitespace or other characters from both sides of':a
string.
ucfirsu) Converts the first character of a string to uppercase..
ucwordsO Converts the first character of each word in a string to
uppercase.
vfprintft) Writes a formatted string to a specified output stream.
vprintf() Outputs a formatted string.
vsprintft) Writes a formatted string to a variable.
wordwrapt) Wraps a string to a given number of characters.
Eagle's Web Development Using PHP

The working of some of the above functions is given below in detail.


1. strlenO function : This function is used to find the length of a string. This function
accepts the string as argument and returns the length or number of characters in the string.
Example:
<?php
echostrlen("Helio Eagle Prakashanl"):
?>
Output
22
2. strrevO function : This function is used to reverse a string. This function accepts a
string as argument and returns its reversed string.
Example:
.<?php
echostrrev("Hello Eagle Prakashanl"):
?>
Output
!nahsakarP elgaE olleH

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".

Edit Format v_ Help

<form action="welcome.php" metbod="get">


Name: <input type="text" name=vname''/>
<input type="submit" value="visit"/>
</form> I
Fig. 2.26. Code to create a form.
Eagle's Web Development Using PHP

(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
••••

Fig. 2.28. Output of HTML form 'file.

(v) Click "visit" button to see the PHP file as shown below

Welcome, Eagle Prakashan


Fig. 2.29. Output of PHP file showing get method.

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

echo "Welcome: $name, your password is: secured with u~";


I ?>

Fig. 2.31. 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/post_eg.html, the following Window will
be seen:

Name: eagle
Password: I ••••••••••
L _._._. _.._ . . ...l

Fig. 2.32. Output of HTML form file.

(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

Welcome: eagle, your password is: secured


with us
Fig. 2.33. Output of PHP file showing get method.

.. 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

II Calling the function


funcEagleO;

?>
Output
This is Eagle Prakashan

• 2.13.2. Function Parameters or Arguments


The information or variables, within the function's parerithesis, are called parameters. These
are used to hold the values executable during runtime. A user is free to take in as many
parameters as he wants, separated with a comma (,) operator. These parameters are used to
accept inputs during runtime. While passing the values like during a function call, they are
called arguments. An argument is a value passed to a function and a parameter is used to hold
those arguments. In common term, both parameter and argument mean the same. We need to
keep in mind that for every parameter, we need to pass its corresponding argument.
Syntax :
function function_name($first_parameter, $second~parameter) {
executable code;

Example:
<html>
<body>

<?php

II function along with three parameters


function Product($numl, $num2, $num3)
{
$result = $numl if $num2 if $num3;
echo "The product is $result";

II Calling the function


II Passingthree arguments
Product(2, 3, 5);
7>
</body>
</html>
Eagle's Web Development Using PHP

Output
The product is 30.

• 2.13.3. Setting Default Values for Function parameter


PHP allows us to set default argument values for function parameters. If we do not pass
any argument for a parameter with default value then PHP will use the default set value for
this parameter in the function call.
Example:
<html>
<body>

<?php

II function with default parameter


function my($str, $num=12)

echo "Sstr is $num years old <br> ":

II Calling the function


rnyt'Rarn", 15);

myt''Adarn"): II In this call, the default value 12


II will be considered
?>
</body>
</html>

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.

• 2.13.4. Returning Values from Functions


Functions can also return values to the part of program from where it is called. The return
keyword is used to return value back to the part of program, from where it was called. The
PHP
returning value may be of any type including the arrays and objects. The return statement also
marks the end of the function and stops the execution after that and returns the value.
Example:
<html>
.. <body>

<?php

l/ function along with three parameters


function product($numl, $num2, $num3)
{
$result = $numl * $num2 * $num3;
return $result; Ilreturning the product

II storing the returned value


$retValue = product(2, 3, 5);
echo "The product is $retValue";

?>

</body>
</html>

Output' :
The product is 30.

• 2.13.5. Parameter passing to Functions


PHP allows us two ways in which an argument can be passed into a function :
1. Pass by value: On passing arguments using pass by value, the value of the argument
gets changed within a function, but the original value outside the function remains unchanged.
That means a duplicate of the original value is passed as an argument.
2. Pass by reference : On passing arguments as pass by reference, the original value is
passed. Therefore, the original value gets altered. In pass by reference we actually pass the
address of the value, where it is stored using ampersand sign (&).
Example:
<html>
<body>

<?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

.. 2.14, INTRODUCTION TO COOKIES


Cookies are small files which are stored on a user's computer. They are used to hold a
modest amount of data specific to a particular client and website and can be accessed either by
the web server or by the client computer. When cookies were invented, they were basically'
little documents containing information about you and your preferences. For instance, when you
select your language in which you want to view your website, the website would save the
information in a document called a cookie on your computer and the next time when you visit
the website, it would be able to read a cookie saved earlier. That way the website could
remember your language and let you view the website in your preferred language without having
to select the language again.
PHP

The Fig. 2.34 below explains the concept and working of cookies.

Web client (Browser) HttplWeb server

New HTTP request


CDr-~======~----------~
:Form-::_-data---:
:_~~~~::. ti_~.?_!l.?J1
HTTP response with cookie ®
~---------:-::-::-::-='======:-::-:;-----I2
i--- H-TIP/1~1-20-0OK:
:_~~~-~~~~~e_
~~c!:'_!?~_:
HTTP request + cookie
GDr-~====~===~------~
:G-ETlprof~e-HTfpi1~1:
:_~??!<!~
~l~_=:. ~ .?_~ ]
HTTP response with cookie IA\
~----~===~========--~~
:--------HTIP/1~1266oK-:
: Hi Harshal, welcome back! :
'---------~-------------'
Session established server figured out
correct user.
Fig. 2.34. ConceptIWorking of cookie.
A cookie can contain any type of information such as the time when you visited the website,
the items that you added into your shopping basket, all the links you clicked in website, etc.
• 2.14.1.Who can access?
If a cookie is created in a particular website and you visit another website later, the latter
would not be able to read the contents from the first website. Cookie is not shared
among different browsers. Means, one browser cannot read the cookie stored by another browser
even if it is in same domain. Also, HTTP cookies can be read by JavaScript. However, JS
code running on a browser can only access cookies set by its domain under which it is running.
It cannot access other domain's cookies. As per HTTP protocol, size of the cookiescannot be
greater than 4 KB. Number of cookiessent by web server for a givendomaincannot be unlimited.
• 2.14.2.Types of Internet Cookies
The various types of Internet cookies are as the following
1. Session cookies: A session cookie only lasts for the duration of users using the website.
A web browser normally deletes session cookies when it quits. A session cookie expires if the
user does not access the website for a period of time chosen by the server (idle timeout). They
only last for the duration of time we are on the site. If someone comes and uses our computer,
they would not be able to see anything on the sites that use session cookies, because they need
to enter the username and password again.
2. Persistent cookies : A persistent cookie outlasts user sessions. If a persistent cookie has
its maximum age 1 year, then within a year, the initial value set in the cookie would be sent
back to the server every time the user visits the server. This could be used to record a vital
piece of information such as how the user initially came to the website. For this reason, persistent
cookies are also called tracking cookies. These are kind of cookies are used on websites that
- Eagle's Web Development Using PHP

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

Fig. 2.35. Reception and transmission of cookie.

• 2.14.4. Storage of cookies at client side


To set/store a cookie in PHP, the setcookiet) function is used. The setcookiet) function needs
to be called prior to any output generated by the script otherwise the cookie will not be set.
Syntax :
setcookie(name, value, expire, path, domain, security);

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...

Save page as ..•

..

Fig. 2.36. Go to developers tool In browser.


.1081 Eagle's We~ Development Using PHP

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.

Fig. 2.37. Cookie stored .

• 2.14.5. Using information of cookies


For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an
associative array that contains a record of all the cookies values sent by the browser in the
current request. The records are stored as a list where cookie name is used as the key. To
access or use a cookie named "Eagle Prakashan" and to check whether a cookie is set or not,
the PHP isseu) function is used in the following code
~ "cookie_eg~Notepad
file Edit Format View Help

<!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.

The following output will be shown on "Localhost"

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

Cookie 'user' is deleted.


Fig. 2.41. Cookie Is deleted.

.. 2.15. CREATING SINGLE OR MULTIPLE SERVER·SIDE SESSIONS


.2.15.1. Whatis a PHP session?
A session is a mechanism to persist information across the different web pages to identify
users as they navigate a site or app. Are you wondering why sessions are needed for a website?
To see why sessions are necessary, we have to go back and see how the HTTP protocol is
designed to work. The HTTP protocol is a stateless protocol, which means that there's no way
a server can remember a specific user between multiple requests. For example, when you access
a web page, the server is just responsible for providing the contents of the requested page. So,
when you access other pages of the same website, the web server interprets each and every
request separately, as if they were unrelated to one another. There's no way for the server to
know that each request originated from the same user.
The following diagram depicts the HTTP protocol in a nutshell.

a resource

Responds with a resource

Fig. 2.42. Working of HTTP protocol.

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

Server responds with a resource


and a unique SESSION 10

Subsequent requests contain


the SESSION 10

Server remembers the user from


the SESSION 10 and returns
personalized response
Fig. 2.43. Concept of session In PHP using cookies.

• 2.15.2. Single server-side PHP Session


.... 2.15.2.1. Start a session
A PHP session is easily started by making a call to the session_startO function. This function
first checks if a session is already started and if none is started then it starts one. It is
recommended to put the call to session_startt) at the beginning of the page.
Eagle's Web Development Using PAP

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>

Fig. 2.44. Start a session and set session variables.

Output of the code above can be seen in "localhost".

m_+_"' ..

Welcome! to session class


All Session variables are set.
Fig. 2.45. Session started.

.... 2.15.2.2. Use the session variables


Next, we create another page called "session_use.php". From this page, we will access the
session information we set on the first page ("session_start.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_staruj).
Also notice that all session variable values are stored in the global $_SESSION variable.
The following example starts a session then register a variable called counter that is incremented
PHP
each time the page is visited during the session. The code also makes use of issett) function to
check if session variable is already set or not.
IIsession_use - Notepad x
File Edit Format View Help

<?php
session_startO;
?>
<!DOCTYPE html>
<html>
<body>

<?php
if( isset( $_ SESSION['counter'] ) ) {
$_ SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}

$msg = "You have visited this page If. $_SESSION['counter'];


$msg .= "time in this session. <br»]';
echo ( $msg );
II Echo session variables that were set on previous page
echo "My favorite Publisher is" . $_SESSION["fav_publisher"] . ".<br>";
echo "And my favorite subject is" . $_ SESSION["fav _subject"] . ".";
?>

</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 .....

Please enter the username or password againl


Fig. 2.49. Output of login.php.

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

Welcome Eagle PrakashanL,Qg out


Fig. 2.51. Output of homepage.php after clicking the "Sign In" button.
After 1 minute elapsed without any event from user, when the user needs to work
again on the page the output will be :

.' Ci (!l
ni~.·~\Qtil!1

Your session has expired! L,Qginhere


Fig. 2.52. Output when session expired.

;npte : Just refresh the page to see this output.


4. The user can forcefully logout by clicking on the "logout" link. For that write the
code shown below and save the file as "logout.php".
- a

<?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_ ...., ......

Click Here to Login


Fig. 2.54. Output of logout.php.
PHP

.2.15.4. Multiple server-side session in PHP


There is a separate $_SESSION created for each user. This is all done by the server, you
as a developer need not to worry to create multiple sessions for different users. When writing
your code, treat the $_ SESSION as if there was only one user on the site. On the other hand,
multiple session variables can be created (already done in the above examples).

• ' 2.16. EVENT MANAGEMENT IN PHP


Event means any happening, like of a button is an event. PHP manages all events very
efficiently. Websites like Facebook, Wikipedia etc. manage user clicked events with PHP code.

., 2.17. INTRODUCTION TO CONTENT MANAGEMENT SYSTEMS BASED ON PHP


Content Management System (or CMS) is a framework already designed by other
programmers and coders on which you can either contribute your knowledge and skills, or just
use those coders' skills to design your own website or blog. Content Management System (CMS)
can be defmed as a tool or software program containing a set of interrelated programs used for
creating and managing different digital or online content. While today we have many open source
CMS available in the market. The choice depends upon our app requirements. Whether you
want to build a simple dynamic website or a fully functionalE-commercestore. There are multiple
types of CMSs available in the market which could lessen your workload. These CMS platforms
help reducing conventional workload of developers. The dynamic web apps which goes up to
thousand pages with time, is easier to develop with CMS platforms. As it streamlines the jobs
involved in development in smart ways. Some famous examples of CMS software developed in
PHP are Joomla, Drupal, WordPress, Magento, etc. The typical use of CMS is in two areas
1. Enterprise Content Management (ECM) and
2. Web Content Management (WCM).
A content management system is composed of two major components. These are:
1. A content management application (CMA) is a graphical user interface that allows its
users to create, delete, modify and publish content even without the knowledge of HTML
or other programming languages that are necessary to create web pages.
2. A content delivery application (CDA) is responsible for the back-end services.. It manages
as well as delivers content after framed in the CMA.
Features of content management system : The various features of content management
system are as the following :
1. User management : This permits the management of user information like the roles of
different users allotted to work simultaneously, such as creating or deleting the user, change the
usemame, password and other related information.
2. Theme system .: This allows us to modify the site view as well as functionality using
stylesheets, images and templates.
3. Extending plugins : Different plugins are offered, which gives custom functionalities
and features to create the CMS site.
Eagle's Web Development Using PHP

4. Search engine optimization : It is embedded with a lot of search engine optimization


(SEQ) tools making content SEQ more straightforward.
5. Media management: It is used for managing the media files and folder, with uploading
media contents easy and effortless.
6. Multilingual: Translation of the language, as preferred by the user, is possible through
CMS.
Advantages of content management system : The various advantagesof content management
system are as the following :
1. Most of the CMS is open source and is available for free.
2. Easy and quick uploading of media files can be done.
3. Several SEQ tools make on-site SEQ simpler.
4. Easy customization is possible as per the need of the user.
S. It can modify CSS files as per the design needed by the user.
6. Many templates and plugins are available for free. Customization of plugins is also
possible.
Disadvantages of content management system : The various disadvantages of content
management system are as the following :
1. CMS software needs a time-to-time update and hence, the user needs to look out for
an updated version.
2. The use of different plugins can make your website heavy and challenging to run.
3. CMS hosting is quite expansive.
4. PHP knowledge is required to modify or change the WordPress website.

•• Impo~ant and Expected Q",estions.,.


What is a variable ?
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. _

What is a static variable ?


A static variable is again a variable with local scope. But the difference with the regular
;.. '. II local variable is that it is not destroyed outside the scope boundary.
~', ~
.'

• 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.

The CMS is used in two areas


Enterprise Content Management (ECM) and
Web Content Management (WCM).
How we can write comments in PHP ?
PHP supports two types of comment :
(i) 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 world!!!";

also a single line comment

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;

What are the various PHP operators ?


The various arithmetic operators are as the following
(i) Logical or Relational operators
Comparison operators
Conditional or Ternary operators
Assignment operators
(v) Array operators
(vi) Increment/Decrement operators
(vii) String operators.
Eagle's Web Development Using PHP

are decision making statements in PHP ?


PHP conditional statements allow you to make a decision, based upon .the result of a condition.
These statements are called as Decision Making Statements or Conditional Statements. It's
just like a two-way path. If you want something then go this way or else tum that way. To
this feature, PHP provides us with four conditional statements :
if statement
if.. .else statement
if. ..elseif. ..else statement
switch statement.

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

Explain strlent) function.


strlenO function : This function is used to find the length of a string. This function accepts
the string as argument and return the length or number of characters in the string.
For example
<?php
echostrlen("Helio Eagle Prakashan!");
PHP
What is a cookie ? -
Cookies are small files which are stored on a user's computer. They are used to hold a modest
amount of data specific to a particular client and website and can be accessed either by the
web s~rver or by the client computer. When cookies were invented, they were basically little
documents containing information about you and your preferences. For instance, when you select
your language in which you want to view your website, the website would save the information
in a document called a cookie on your computer and the next time when you visit the website,
. it would be able to read a cookie saved earlier. That way the website could remember your
language and let you view the website in your preferred language without having to select the
language again. A cookie can contain any type of information such as the time when you visited
the website, the items that you added into your shopping basket, all the links you clicked in
website, etc.

What are the various features of PHP ?


, The various features of PHP are as the following
(i) PHP is open source and free, thus, one can freely download, install and start developing/
using it.
(ii) PHP has a very simple and easy to understand syntax, hence the learning curve is smaller
as compared to other scripting languages like JSP, ASP etc.
(iii) 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.
(iv) All the popular web hosting services support PHP. Also, the web hosting plans for PHP
are generally the amongst the cheapest plans because of its popularity.
(li) Popular content management systems like Joomla, Drupal etc. are developed in PHP and
if you want to start your own website like Studytonight, you can easily do that with PHP.
(vi) With PHP, you can create static and dynamic webpages, perform file handling operations,
send E-mails, access and modify browser cookies, and almost everything else that you
might want to implement in your web project.
(vii) PHP is fast as compared to other scripting languages like JSP and ASP.
(viii) PHP has in-built support for MySQL, which is one of the most widely used database
management system.

Write down some important applications of PHP.


Some important applications of PHP are as the following
(I) It can be used to create Web applications like Social Networks (Facebook, Digg), Blogs
(Wordpress, Joomla), eCommerce websites (OpenCart, Magento etc.) etc.
(ii) Command Line Scripting. You can write PHP scripts to perform different operations on
any machine, all you need is a PHP parser for this.
(iii) Create Facebook applications and easily integrate Facebook plugins in your website, using
Facebook's PHP SDK.
(iv) Sending E-maiIs or building E-mail applications because PHP provides with a robust E-
mail sending function.
Eagle's Web Development Using PHP
rules for PUP variables ?
Rules for PHP variables are as the following :
(I) A'variable starts with the $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number,
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
Variable names are case-sensitive ($age and $AGE are two different variables).
Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
Variables do not need, to be declared before assignment.
(viii) 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.
Write down some disadvantages of content management system.
various disadvantages of content management system are as the following: '
eMS software needs a time-to-time update and hence, the user needs to look out for an
updated version.
The use of different plugins can make your website heavy and challenging to tun.
eMS hosting is quite expansive.
PHP knowledge is required to modify or change the WordPress website.

•• 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.

~ Write the full form ....


1. PHP
2. eMS

~ State true or false .....


1. PHP .is not a cross-platform language.
2. PHP is built by Joomla.
3. PHP is case sensitive.
4. A variable name can only contain alpha-numeric characters and underscores.
PHP

Fill in the blanks


1. open source
ANSWERS

2. server-side 3. $ . sign, name


-
4. Multi-dimensional
Write the full form
1. Hypertext Preprocessor 2. Content Management System
State true or false :
1. False 2. False 3. True 4. True

•• 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

You might also like