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

php-pw

The document is a participant's workbook for a course on Web Developments Using PHP at the Tata Institute of Social Sciences. It covers various topics including the introduction to PHP, its advantages, server-side architecture, data types, functions, and database connectivity. The workbook is structured into units with detailed explanations, examples, and activities for practical understanding of PHP programming.

Uploaded by

ronak.kdc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

php-pw

The document is a participant's workbook for a course on Web Developments Using PHP at the Tata Institute of Social Sciences. It covers various topics including the introduction to PHP, its advantages, server-side architecture, data types, functions, and database connectivity. The workbook is structured into units with detailed explanations, examples, and activities for practical understanding of PHP programming.

Uploaded by

ronak.kdc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 164

Bachelor/BSc in Software Development

Undergraduate Diploma - Second Year


SEMESTER-I
Web Developments Using PHP
PARTICIPANT’S WORKBOOK

Tata Institute of Social Sciences – School of Vocational Education


--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

_____________________________________________________________________________
2 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Table of Contents
B. VOC. IN SOFTWARE DEVELOPMENT........................................................................................ 1
PARTICIPANT GUIDE ................................................................................................................................... 1
WEB DEVELOPMENTS USING PHP ................................................................................................. 1
...................................................................................................................................................................... 3
UNIT I ........................................................................................................................................................ 13
Introduction to PHP as a programming Language ..................................................................... 13
Advantages of PHP ................................................................................................................................ 13
#1 – FREE OF COST ............................................................................................................................ 13
#2 – CAPABLE ........................................................................................................................................ 13
#3 – EASY ................................................................................................................................................ 14
#4 – PLATFORM INDEPENDENT ..................................................................................................... 14
#5 – SUPPORTS ALL MAJOR WEB SERVERS............................................................................. 14
#6 – SUPPORTS ALL MAJOR DATABASES .................................................................................. 14
#7 – FASTER DEVELOPMENTS ....................................................................................................... 14
#8 – SECURE .......................................................................................................................................... 14
#9 – LARGE COMMUNITIES.............................................................................................................. 14
#10 – PROVEN AND TRUSTED ........................................................................................................ 14
The server side architecture Decomposed .................................................................................... 14
Architecture Diagram of PHP based web applications .............................................................. 14
Architecture Diagram .......................................................................................................................... 15
Overview of PHP ..................................................................................................................................... 16
How Does PHP Work? .......................................................................................................................... 16
Why is PHP so Useful? ........................................................................................................................ 17
History ...................................................................................................................................................... 18
PHP Tools, FI, Construction Kit, and PHP/FI .............................................................................. 18
PHP 3......................................................................................................................................................... 20
PHP 4......................................................................................................................................................... 20
PHP 5......................................................................................................................................................... 21
Object oriented support ...................................................................................................................... 21

_____________________________________________________________________________
3 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Object Oriented Concepts .................................................................................................................. 21
Defining PHP Classes ........................................................................................................................... 22
Example.................................................................................................................................................... 23
<?php ........................................................................................................................................................ 23
Creating Objects in PHP ..................................................................................................................... 24
Calling Member Functions ................................................................................................................. 24
Constructor Functions ........................................................................................................................ 25
Destructor................................................................................................................................................ 26
Inheritance .............................................................................................................................................. 26
<definition body>................................................................................................................................... 26
Function Overriding ............................................................................................................................. 27
Public Members ..................................................................................................................................... 28
Private members .................................................................................................................................... 28
Protected members ............................................................................................................................... 29
Interfaces ................................................................................................................................................. 29
Constants................................................................................................................................................. 30
Abstract Classes .................................................................................................................................... 30
Static Keyword ....................................................................................................................................... 31
Final Keyword......................................................................................................................................... 32
<?php ........................................................................................................................................................ 32
Calling parent constructors ............................................................................................................... 32
Benefits in running PHP as a server side script ......................................................................... 34
Advantages of Server-Side Scripting ............................................................................................... 34
Some of the advantages of server-side scripting are: ................................................................ 34
Installing a web server......................................................................................................................... 34
Internet information server and IIS installation ......................................................................... 35
To install Internet Information Services ........................................................................................ 35
Activity: (Answer the following questions) ..................................................................................... 35
Activity-2:................................................................................................................................................. 35
UNIT II....................................................................................................................................................... 37
The basics of PHP, data types ........................................................................................................... 37

_____________________________________________________________________________
4 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Integers ..................................................................................................................................................... 37
1998........................................................................................................................................................... 37
+33 ............................................................................................................................................................. 37
Use the is_int( ) function (or its is_integer( ) alias) to test whether a value is an ............ 38
Floating-Point Numbers ...................................................................................................................... 38
Strings ...................................................................................................................................................... 39
Table 2-1. Escape sequences in double-quoted strings ........................................................... 39
Booleans ................................................................................................................................................... 40
Arrays ........................................................................................................................................................ 41
Hello, Edison........................................................................................................................................... 42
Objects ...................................................................................................................................................... 43
Resources................................................................................................................................................. 44
NULL.......................................................................................................................................................... 44
There’s only one value of the NULL data type. That value is available through the ....... 44
Variables .................................................................................................................................................. 45
Yes .............................................................................................................................................................. 46
Variable Variables ................................................................................................................................. 46
Variable References .............................................................................................................................. 46
The old value of $black is lost. Instead, $black is now another name for the value ...... 46
Unsetting a variable that is aliased does not affect other names for that variable’s ...... 47
Variable Scope........................................................................................................................................ 47
Constants................................................................................................................................................. 50
Operators ................................................................................................................................................. 50
Arithmetic Operators ........................................................................................................................... 50
Example.................................................................................................................................................... 51
Addition Operation Result: 62 .......................................................................................................... 52
Comparison Operators ........................................................................................................................ 53
Example.................................................................................................................................................... 53
TEST1 : a is not equal to b................................................................................................................. 54
Logical Operators .................................................................................................................................. 54
Example.................................................................................................................................................... 55

_____________________________________________________________________________
5 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Assignment Operators ......................................................................................................................... 57
Example.................................................................................................................................................... 57
Conditional Operator ........................................................................................................................... 58
Operators Categories ........................................................................................................................... 59
Precedence of PHP Operators ............................................................................................................ 59
Arrays ........................................................................................................................................................ 60
Numeric Array ........................................................................................................................................ 61
Example.................................................................................................................................................... 61
Associative Arrays ................................................................................................................................. 62
Example.................................................................................................................................................... 62
Multidimensional Arrays .................................................................................................................... 64
Example.................................................................................................................................................... 64
Conditional statements (if statement Executing Multiple Statements else if clause and
switch statement) .................................................................................................................................. 65
The If...Else Statement ........................................................................................................................ 66
Syntax ....................................................................................................................................................... 66
Example.................................................................................................................................................... 66
The ElseIf Statement ............................................................................................................................ 67
Syntax ....................................................................................................................................................... 67
Example.................................................................................................................................................... 68
The Switch Statement.......................................................................................................................... 68
Syntax ....................................................................................................................................................... 68
Example.................................................................................................................................................... 69
Iterations (for loop while loop controlling an array using a while loop do while
statement for each loop and special loop key words)............................................................... 70
The for loop statement......................................................................................................................... 71
Syntax ....................................................................................................................................................... 71
Example.................................................................................................................................................... 71
The while loop statement .................................................................................................................... 72
Syntax ....................................................................................................................................................... 72
Example.................................................................................................................................................... 72
The do...while loop statement ........................................................................................................... 73
_____________________________________________________________________________
6 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Syntax ....................................................................................................................................................... 73
Example.................................................................................................................................................... 73
The foreach loop statement................................................................................................................ 73
Syntax ....................................................................................................................................................... 74
Example.................................................................................................................................................... 74
The break statement ............................................................................................................................ 74
Example.................................................................................................................................................... 74
The continue statement ...................................................................................................................... 75
Example.................................................................................................................................................... 75
Activity: (Answer the following questions) ..................................................................................... 76
Activity-2:................................................................................................................................................. 76
UNIT III ..................................................................................................................................................... 78
Functions ................................................................................................................................................. 78
Calling a Function ................................................................................................................................ 78
Defining a Function .............................................................................................................................. 79
If you define your function with the optional ampersand before the name, the function
.................................................................................................................................................................... 80
Let’s take a look at a simple function. Example 3-1 takes two strings, concatenates ... 80
Example 3-1. String concatenation................................................................................................. 80
Because the return statement can accept any expression, even complex ones, we can
.................................................................................................................................................................... 80
Example 3-2. String concatenation redux .................................................................................... 80
<?= 'A pair of 13s is ' . doubler(13); ?> ........................................................................................... 81
User defined functions ........................................................................................................................ 82
Elements of a function ........................................................................................................................ 82
Example : PHP function ...................................................................................................................... 83
Figure 3.1................................................................................................................................................. 83
Example : Functions within functions ........................................................................................... 83
Figure 3.2................................................................................................................................................. 84
Functions with arguments ................................................................................................................. 84
Passing Arguments by Reference ..................................................................................................... 86
PHP Functions returning value ........................................................................................................ 87
_____________________________________________________________________________
7 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Built in functions( print() include() header() phpinfo() ) ........................................................ 87
PHP print() Function ............................................................................................................................ 88
Definition and Usage ............................................................................................................................ 88
Syntax ....................................................................................................................................................... 88
Technical Details ................................................................................................................................... 88
include() .................................................................................................................................................... 89
<a href="http://www.tutorialspoint.com/index.htm">Home</a> -..................................... 89
PHP header() Function......................................................................................................................... 90
Definition and Usage ............................................................................................................................ 90
Syntax ....................................................................................................................................................... 91
Example 1 ................................................................................................................................................ 91
phpinfo...................................................................................................................................................... 92
Description ¶ .......................................................................................................................................... 92
Parameters ¶ ........................................................................................................................................... 92
Return Values ¶ ..................................................................................................................................... 93
Returns TRUE on success or FALSE on failure. ......................................................................... 93
PHP server Variables ............................................................................................................................ 93
$_SERVER ............................................................................................................................................... 93
Working with date and time .............................................................................................................. 96
Getting the Time Stamp with time() ................................................................................................ 96
Converting a Time Stamp with getdate() ....................................................................................... 96
Following table lists the elements contained in the array returned by getdate(). ............ 96
Example.................................................................................................................................................... 98
Converting a Time Stamp with date() ............................................................................................. 99
Example.................................................................................................................................................. 101
Performing mathematical operations ........................................................................................... 101
abs............................................................................................................................................................ 103
Description ¶ ........................................................................................................................................ 103
Parameters ¶ ......................................................................................................................................... 103
Return Values ¶ ................................................................................................................................... 103
Examples ¶ ............................................................................................................................................ 103

_____________________________________________________________________________
8 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Example #1 abs() example................................................................................................................ 103
acos — Arc cosine ............................................................................................................................... 103
Description ¶ ........................................................................................................................................ 104
Parameters ¶ ......................................................................................................................................... 104
The argument to process .................................................................................................................. 104
Return Values ¶ ................................................................................................................................... 104
The arc cosine of arg in radians..................................................................................................... 104
acosh — Inverse hyperbolic cosine ............................................................................................... 104
Description ¶ ........................................................................................................................................ 104
Parameters ¶ ......................................................................................................................................... 104
The value to process........................................................................................................................... 104
Return Values ¶ ................................................................................................................................... 104
The inverse hyperbolic cosine of arg ............................................................................................. 104
exp — Calculates the exponent of e .............................................................................................. 105
Description ¶ ........................................................................................................................................ 105
Returns e raised to the power of arg. ........................................................................................... 105
Note: ........................................................................................................................................................ 105
Parameters ¶ ......................................................................................................................................... 105
The argument to process .................................................................................................................. 105
Return Values ¶ ................................................................................................................................... 105
Examples ¶ ............................................................................................................................................ 105
Example #1 exp() example................................................................................................................ 105
The above example will output: ...................................................................................................... 105
Working with string functions ........................................................................................................ 106
String Concatenation Operator ...................................................................................................... 107
Hello World 1234................................................................................................................................. 107
Using the strlen() function ............................................................................................................... 107
Using the strpos() function .............................................................................................................. 108
System Variable (GET POST cookies& Session Forums) ................................................... 108
The GET Method.................................................................................................................................. 108
The POST Method ............................................................................................................................... 110

_____________________________________________________________________________
9 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
The $_REQUEST variable ................................................................................................................. 111
COOKIES ............................................................................................................................................... 111
The Anatomy of a Cookie .................................................................................................................. 112
Setting Cookies with PHP ................................................................................................................. 113
SESSIONS.............................................................................................................................................. 113
Starting a PHP Session...................................................................................................................... 114
Destroying a PHP Session ................................................................................................................ 116
Activity-1: (Answer the following questions)............................................................................... 116
Activity-2:............................................................................................................................................... 116
UNIT IV ................................................................................................................................................... 118
Working with forms ............................................................................................................................ 118
Security Measures: Forms Are Not Trustworthy ...................................................................... 118
Verification Strategies........................................................................................................................ 118
Fetching Form Variables Consistently and Safely ................................................................... 119
Trimming Excess Whitespace ......................................................................................................... 120
Importing Form Variables into an Array ..................................................................................... 121
Figure: A form with an array of checkboxes............................................................................... 122
Form elements (Text Area Password Radio Button The Combo Box Hidden Field and
image) ...................................................................................................................................................... 122
PHP script for SELECT OPTION FIELD: ...................................................................................... 122
<form action="#" method="post"> .................................................................................................. 123
Hidden Fields........................................................................................................................................ 125
Using Hidden Fields to Save State ................................................................................................ 125
TIP ............................................................................................................................................................ 126
CAUTION ................................................................................................................................................ 127
Image ....................................................................................................................................................... 127
GET /page.html HTTP/1.0 .............................................................................................................. 127
The web server sends back a response to each of these requests. The Content-Type . 128
Content-Type: text/html ................................................................................................................... 128
Uploading files to the Web Server using PHP ............................................................................ 128
The process of uploading a file follows these steps.................................................................. 128

_____________________________________________________________________________
10 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Creating an upload form ................................................................................................................... 129
Creating an upload script ................................................................................................................. 130
Building a challenge and response subsystem and understanding the functionality of
the FORM attribute Method ............................................................................................................ 132
<FORM NAME ="form1" METHOD =" " ACTION = ""> ............................................................. 133
<FORM NAME ="form1" METHOD ="GET" ACTION = ""> ...................................................... 133
?Submit1=Login................................................................................................................................... 134
Regular Expressions: Engine, Types of Regular Expressions, symbols used in Regular
Expressions ........................................................................................................................................... 134
POSIX Regular Expressions............................................................................................................. 134
Brackets ................................................................................................................................................. 135
Quantifiers: ........................................................................................................................................... 135
Examples ............................................................................................................................................... 136
Predefined Character Ranges .......................................................................................................... 137
PHP's Regexp POSIX Functions...................................................................................................... 137
PERL Style Regular Expressions .................................................................................................... 138
Metacharacters .................................................................................................................................... 138
Modifiers................................................................................................................................................. 139
PHP's Regexp PERL Compatible Functions ................................................................................ 139
Error handling in PHP, Displaying errors, warnings ............................................................... 140
Using die() function ............................................................................................................................ 140
Defining Custom Error Handling Function ................................................................................ 140
Syntax ..................................................................................................................................................... 141
Possible Error levels ........................................................................................................................... 141
types of errors, error levels in PHP (covered above) ................................................................. 143
logging Errors and Ignoring errors. ............................................................................................... 143
Error Handling Functions ................................................................................................................ 143
Sets a user function (error_handler) to handle errors in a script. ...................................... 144
Installation ............................................................................................................................................ 146
Runtime Configuration ...................................................................................................................... 146
PHP Error and Logging Constants................................................................................................. 147
Activity: (Answer the following questions) ................................................................................... 147
_____________________________________________________________________________
11 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Activity-2 ................................................................................................................................................ 147
UNIT V .................................................................................................................................................... 149
Data base connectivity using PHP (MySQL ODBC ORACLE SQL), Performing
executing Commands ........................................................................................................................ 149
What you should already have? ..................................................................................................... 149
You should establish a connection to the MySQL database. ............................................... 150
Unable to select database................................................................................................................. 151
How to Display MySQL Table Data ............................................................................................... 152
SELECT * FROM table name ........................................................................................................... 153
$i=0;while ($i < $num) {CODE$i++;} ............................................................................................. 154
<? echo $variablename; ?>............................................................................................................... 155
Different types of Data Base Operations like Insertion deletion update and query on
data .......................................................................................................................................................... 158
Running MYSQL Queries In PHP ................................................................................................... 158
Handling MYSQL Query Results In PHP ..................................................................................... 159
Summary: .............................................................................................................................................. 161
Activity-1: (Answer the following questions)............................................................................... 161
Activity-2 ................................................................................................................................................ 161

_____________________________________________________________________________
12 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
UNIT I
Introduction to PHP as a programming Language
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web
developers to create dynamic content that interacts with databases. PHP is basically
used for developing web based software applications.

PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way
back in 1994.

PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

PHP is a server side scripting language that is embedded in HTML. It is used to


manage dynamic content, databases, session tracking, even build entire e-commerce
sites.
It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache
module on the Unix side. The MySQL server, once started, executes even very complex
queries with huge result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and CORBA),
making n-tier development a possibility for the first time.
PHP is forgiving: PHP language tries to be as forgiving as possible.

PHP Syntax is C-Like.

Advantages of PHP
PHP web development means developing websites and dynamic web pages using the
versatile and capable server-side scripting language, PHP. It offers a plethora of
benefits. Not only is it open-source but also feature-rich and has all the functionality
that a proprietary or paid scripting language would offer. Here are a few benefits that
have made PHP web development so sought after.

#1 – FREE OF COST
PHP is open source and is developed and updated by a community of developers from
around the globe. Therefore, all its components are free to use and distribute.

#2 – CAPABLE
It can be used to design any type of website and can handle websites with a lot of
traffic. Facebook, Twitter, Wikipedia and many other very widely visited websites use it
as their framework. And because it is server-side scripting, it can do anything that
other CGI programs can do.

_____________________________________________________________________________
13 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
#3 – EASY
It has a readable and easily understandable syntax. Its code is embedded in the HTML
source code and it is based on C/C++. Therefore, it is very familiar and programmers
are very comfortable coding with it.

#4 – PLATFORM INDEPENDENT
It can be run on all major operating systems like Linux, UNIX, Mac OS and Windows.

#5 – SUPPORTS ALL MAJOR WEB SERVERS


It supports all major web servers like Apache, Microsoft IIS, Netscape, personal
webserver, iPlanet server, etc.

#6 – SUPPORTS ALL MAJOR DATABASES


IT supports all major databases including MySQL, dBase, IBM DB2, InterBase,
FrontBase, ODBC, PostgreSQL, SQLite, etc.

#7 – FASTER DEVELOPMENTS
It uses its own memory space and thus decreases the loading time and workload from
the server. The processing speed is fast and web applications like Ecommerce, CRM,
CMS and Forums are also developed faster by it.

#8 – SECURE
It has multiple layers of security to prevent threats and malicious attacks.

#9 – LARGE COMMUNITIES
It has a large community of developers who regular and timely updates tutorials,
documentation, online help and FAQs.

#10 – PROVEN AND TRUSTED


It is being used since close to two decades now since its inception in 1995. It is trusted
by thousands of websites and developers and the list is increasing day by day. It has
also proven its capability and versatility by developing and maintaining some of the
most highly visited and popular websites.

The server side architecture Decomposed


http://letsdophp.blogspot.in/p/architecture-diagram-of-php-based-web.html

Architecture Diagram of PHP based web applications

Now put all these together and see how they work actually. An Architecture Diagram is
a logical diagram that shows how each of the components in a system is connected
with each other and how are the data flowing between. If we draw architecture
diagram for a typical PHP based web application it will be like the below diagram.

_____________________________________________________________________________
14 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Architecture Diagram

Now discuss over it little more. The numbers I used below beside the Label names
following 1 for Request flow and 2 for response flow.

A1: First user accessed the website through browser. That means user types the URL
of the website in browser and hit go.

B1: The page request on browser will reach to the Web Server (Apache).

C: Web server will collect that requested page (HTML or PHP or Image file etc) from its
document root. (In our example it will be www folder in WAMP. You will see it in next
one)

B2: Now if it is a static element like HTML, CSS, image file or Java Script file then
Apache will send it directly to browser.
A2: And Browser will render it to user on screen

D1: If it is a PHP file then Apache sends the content of the file to PHP Interpreter. PHP
interpreter interprets the PHP code and executes it. if DB operation is required it
performs the same (E)

D2: PHP Interpreter generates output (if the PHP code is to generate any output) and
sends to Apache

B2: Apache sends that content to browser

_____________________________________________________________________________
15 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
A2: Browser renders it to users' screen

All static components like HTML, CSS files, Image File, Java Scripts etc doesn't need
interpreter. Our web browsers are built to render them and display on screen properly.
That is why if user requests for these kinds of components Apache collects them from
Document root and sends back to Browser directly.

Only if requested page is a PHP page Apache will send it to PHP interpreter to get it
translated and executed.

That is why though those listed static components reside on Server we will consider
them as part of User Interface and as they get rendered at user's browser we may refer
them as Client side components. In web technology Browsers are Client terminals.

And for similar reason we will refer PHP files as Server side components as they have
dependencies on another Server Side component PHP Interpreter and cannot be
executed only on browsers.
Now let me explain the keywords of the definition as you will be able to understand
them better

1. PHP files are kept on Server (in Document root) - Server Side
2. PHP Interpreter interprets PHP language and executes instructions as per code.
It does not need compilation( This is way deep and different topic to discuss in a
separate forum) - Scripting language

Overview of PHP
PHP is an intuitive, server side scripting language. Like any other scripting language it
allows developers to build logic into the creation of web page content and handle data
returned from a web browser. PHP also contains a number of extensions that make it
easy to interact with databases, extracting data to be displayed on a web page and
storing information entered by a web site visitor back into the database.

PHP consists of a scripting language and an interpreter. Like other scripting


languages, PHP enables web developers to define the behavior and logic they need in a
web page. These scripts are embedded into the HTML documents that are served by
the web server. The interpreter takes the form of a module that integrates into the web
server, converting the scripts into commands the computer then executes to achieve
the results defined in the script by the web developer.

How Does PHP Work?


To develop an understanding of how PHP works it is helpful to first explore what
happens when a web page is served to a user's browser.

When a user visits a web site or clicks on a link on a page the browser sends a request
to the web server hosting the site asking for a copy of the web page. The web server
_____________________________________________________________________________
16 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
receives the request, finds the corresponding web page file on the file system and
sends it back, over the internet, to the user's browser.

Typically the web server doesn't pay any attention to the content of the file it has just
transmitted to the web browser. As far as the web server is concerned the web browser
understands the content of the web page file and knows how to interpret and render it
so that it appears as the web designer intended.

Now let's consider what kind of web page content a web browser understands. These
days a web page is likely to consist of HTML, XHTML and JavaScript. The web browser
contains code that tells it what to do with these types of content. For example, it
understands the structure HTML in terms of rendering the page and it has a
JavaScript interpreter built in that knows how to execute the instructions in a
JavaScript script. A web browser, however, knows absolutely nothing about any PHP
script that may be embedded in an HTML document. If a browser was served a web
page containing PHP it would not know how to interpret that code.

Given that a web browser knows nothing about PHP in a web page, then clearly
something has to be done with any PHP script in the page before it reaches the
browser. This is where the PHP pre-processing module comes in. The PHP module is,
as mentioned previously, integrated into the web server. The module tells the web
server that when a page is to be served which contains PHP script (identified by special
markers) that it is to pass that script to the PHP pre-processing module and wait for
the PHP module to send it some content to replace that script fragment. The PHP
processing module understands PHP, executes the PHP script written by the web
developer and, based on the script instructions creates output that the browser will
understand. The web server substitutes the content provided by the PHP pre-
processor module in place of the PHP script in the web page and sends it to the
browser where it is rendered for the user to view.

Why is PHP so Useful?


In terms of web page content we have two extremes. At one extreme we have HTML
which is completely static. There is very little that can be done with HTML to create
dynamic content in a web page. At the other extreme we have scripting languages like
JavaScript. JavaScript provides a powerful mechanism for creating interactive and
dynamic web pages.

When talking about JavaScript it is important to understand that it is, by design, a


client side scripting language. By this we mean that the script gets executed inside the
user's browser and not on the web server on which the web page originated. Whilst
this is fine for many situations it is often the case that by the time a script reaches the
browser it is then either too late, or inefficient, to do what is needed. A prime example
of this involves displaying a web page which contains some data from a database
table. Since the database resides on a server (either the same physical server which

_____________________________________________________________________________
17 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
runs the web server or on the same network as the web server connected by a high
speed fiber network connection) it makes sense for any script that needs to extract
data from the database to be executed on the server, rather than waiting until it
reaches the browser. It is for this kind of task that PHP is perfectly suited. It is also
fast and efficient (because the script is executed on the server it gets to take advantage
of multi-processing, large scale memory and other such enterprise level hardware
features.

In addition to the advantages of being a server side scripting language PHP is easy to
learn and use. The fact that PHP works seamlessly with HTML makes it accessible to a
broad community of web designers.

Perhaps one of the most significant advantages of PHP to some is the ease with which
it interacts with the MySQL database to retrieve and store data.

History
PHP Tools, FI, Construction Kit, and PHP/FI

PHP as its known today is actually the successor to a product named PHP/FI. Created
in 1994 by Rasmus Lerdorf, the very first incarnation of PHP was a simple set of
Common Gateway Interface (CGI) binaries written in the C programming language.
Originally used for tracking visits to his online resume, he named the suite of scripts
"Personal Home Page Tools," more frequently referenced as "PHP Tools." Over time,
more functionality was desired, and Rasmus rewrote PHP Tools, producing a much
larger and richer implementation. This new model was capable of database interaction
and more, providing a framework upon which users could develop simple dynamic
web applications such as guestbook. In June of 1995, Rasmus » released the source
code for PHP Tools to the public, which allowed developers to use it as they saw fit.
This also permitted - and encouraged - users to provide fixes for bugs in the code, and
to generally improve upon it.

In September of that year, Rasmus expanded upon PHP and - for a short time -
actually dropped the PHP name. Now referring to the tools as FI (short for "Forms
Interpreter"), the new implementation included some of the basic functionality of PHP
as we know it today. It had Perl-like variables, automatic interpretation of form
variables, and HTML embedded syntax. The syntax itself was similar to that of Perl,
albeit much more limited, simple, and somewhat inconsistent. In fact, to embed the
code into an HTML file, developers had to use HTML comments. Though this method
was not entirely well-received, FI continued to enjoy growth and acceptance as a CGI
tool --- but still not quite as a language. However, this began to change the following
month; in October, 1995, Rasmus released a complete rewrite of the code. Bringing
back the PHP name, it was now (briefly) named "Personal Home Page Construction
Kit," and was the first release to boast what was, at the time, considered an advanced
scripting interface. The language was deliberately designed to resemble C in structure,

_____________________________________________________________________________
18 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
making it an easy adoption for developers familiar with C, Perl, and similar languages.
Having been thus far limited to UNIX and POSIX-compliant systems, the potential for
a Windows NT implementation was being explored.

The code got another complete makeover, and in April of 1996, combining the names
of past releases, Rasmus introduced PHP/FI. This second-generation implementation
began to truly evolve PHP from a suite of tools into a programming language in its own
right. It included built-in support for DBM, mSQL, and Postgres95 databases, cookies,
user-defined function support, and much more. That June, PHP/FI was given a
version 2.0 status. An interesting fact about this, however, is that there was only one
single full version of PHP 2.0. When it finally graduated from beta status in November,
1997, the underlying parsing engine was already being entirely rewritten.

Though it lived a short development life, it continued to enjoy a growing popularity in


still-young world of web development. In 1997 and 1998, PHP/FI had a cult of several
thousand users around the world. A Net craft survey as of May, 1998, indicated that
nearly 60,000 domains reported having headers containing "PHP", indicating that the
host server did indeed have it installed. This number equated to approximately 1% of
all domains on the Internet at the time. Despite these impressive figures, the
maturation of PHP/FI was doomed to limitations; while there were several minor
contributors, it was still primarily developed by an individual.

Example #1 Example PHP/FI Code

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->

<!--ifsubstr $exec_result Mozilla-->

Hey, you are using Netscape!<p>

<!--endif-->

<!--sql database select * from table where user='$username'-->

<!--ifless $numentries 1-->

Sorry, that record does not exist<p>

<!--endif exit-->

Welcome <!--$user-->!<p>

You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->

_____________________________________________________________________________
19 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
PHP 3
PHP 3.0 was the first version that closely resembles PHP as it exists today. Finding
PHP/FI 2.0 still inefficient and lacking features they needed to power an eCommerce
application they were developing for a university project, Andi Gutmans and Zeev
Suraski of Tel Aviv, Israel, began yet another complete rewrite of the underlying parser
in 1997. Approaching Rasmus online, they discussed various aspects of the current
implementation and their redevelopment of PHP. In an effort to improve the engine
and start building upon PHP/FI's existing user base, Andi, Rasmus, and Zeev decided
to collaborate in the development of a new, independent programming language. This
entirely new language was released under a new name that removed the implication of
limited personal use that the PHP/FI 2.0 name held. It was renamed simply 'PHP',
with the meaning becoming a recursive acronym - PHP: Hypertext Preprocessor.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In
addition to providing end users with a mature interface for multiple databases,
protocols, and APIs, the ease of extending the language itself attracted dozens of
developers who submitted a variety of modules. Arguably, this was the key to PHP
3.0's tremendous success. Other key features introduced in PHP 3.0 included object-
oriented programming support and a far more powerful and consistent language
syntax.

In June, 1998, with many new developers from around the world joining the effort,
PHP 3.0 was announced by the new PHP Development Team as the official successor
to PHP/FI 2.0. Active development of PHP/FI 2.0, which had all-but ceased as of
November of the previous year, was now officially ended. After roughly nine months of
open public testing, when the announcement of the official release of PHP 3.0 came, it
was already installed on over 70,000 domains around the world, and was no longer
limited to POSIX-compliant operating systems. A relatively small share of the domains
reporting PHP as installed were hosted on servers running Windows 95, 98, and NT,
and Macintosh. At its peak, PHP 3.0 was installed on approximately 10% of the web
servers on the Internet.

PHP 4
By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and
Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to
improve performance of complex applications, and improve the modularity of PHP's
code base. Such applications were made possible by PHP 3.0's new features and
support for a wide variety of third party databases and APIs, but PHP 3.0 was not
designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi),
met these design goals successfully, and was first introduced in mid 1999. PHP 4.0,
based on this engine, and coupled with a wide range of additional new features, was
officially released in May 2000, almost two years after its predecessor. In addition to
_____________________________________________________________________________
20 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
the highly improved performance of this version, PHP 4.0 included other key features
such as support for many more web servers, HTTP sessions, output buffering, more
secure ways of handling user input and several new languages constructs.

PHP 5
PHP 5 was released in July 2004 after long development and several pre-releases. It is
mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of
other new features.

PHP's development team includes dozens of developers, as well as dozens others


working on PHP-related and supporting projects, such as PEAR, PECL, and
documentation, and an underlying network infrastructure of well over one-hundred
individual web servers on six of the seven continents of the world. Though only an
estimate based upon statistics from previous years, it is safe to presume PHP is now
installed on tens or even perhaps hundreds of millions of domains around the world.

Object oriented support


We can imagine our universe made of different objects like sun, earth, moon etc.
Similarly we can imagine our car made of different objects like wheel, steering, gear
etc. Same way there is object oriented programming concepts which assume
everything as an object and implement software using different objects.

Object Oriented Concepts


Before we go in detail, let’s define important terms related to Object Oriented
Programming.

Class is a programmer-defined data type, which includes local functions as well as


local data. You can think of a class as a template for making many instances of the
same kind (or class) of object.

Object individual instance of the data structure defined by a class. Define a class
once and then make many objects that belong to it. Objects are also known as
instance.

Member Variables are the variables defined inside a class. This data will be invisible
to the outside of the class and can be accessed via member functions. These variables
are called attribute of the object once an object is created.

Member functions are the function defined inside a class and are used to access
object data.

Inheritance − When a class is defined by inheriting existing function of a parent class


then it is called inheritance. Here child class will inherit all or few member functions
and variables of a parent class.

_____________________________________________________________________________
21 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Parent class is a class that is inherited from by another class. This is also called a
base class or super class.

Child Class is a class that inherits from another class. This is also called a subclass
or derived class.

Polymorphism is an object oriented concept where same function can be used for
different purposes.

Overloading is a type of polymorphism in which some or all of operators have different


implementations depending on the types of their arguments. Similarly functions can
also be overloaded with different implementation.

Data Abstraction is a representation of data in which the implementation details are


hidden (abstracted).

Encapsulation refers to a concept where we encapsulate all the data and member
functions together to form an object.

Constructor refers to a special type of function which will be called automatically


whenever there is an object formation from a class.

Destructor refers to a special type of function which will be called automatically


whenever an object is deleted or goes out of scope.

Defining PHP Classes


The general form for defining a new class in PHP is as follows −

<?php

class phpClass {

var $var1;

var $var2 = "constant string";

function myfunc ($arg1, $arg2) {

[..]

[..]

?>

Here is the description of each line −


_____________________________________________________________________________
22 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
The special form class, followed by the name of the class that you want to define.

A set of braces enclosing any number of variable declarations and function definitions.

Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a constant
value.

Function definitions look much like standalone PHP functions but are local to the
class and will be used to set and access object data.

Example

Here is an example which defines a class of Books type −

<?php

class Books {

/* Member variables */

var $price;

var $title;

/* Member functions */

function setPrice($par){

$this->price = $par;

function getPrice(){

echo $this->price ."<br/>";

function setTitle($par){

$this->title = $par;

function getTitle(){

echo $this->title ." <br/>";

_____________________________________________________________________________
23 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
}

?>

The variable $this is a special variable and it refers to the same object i.e. itself.

Creating Objects in PHP


Once you defined your class, then you can create as many objects as you like of that
class type. Following is an example of how to create object using new operator.

$physics = new Books;

$maths = new Books;

$chemistry = new Books;

Here we have created three objects and these objects are independent of each other
and they will have their existence separately. Next we will see how to access member
function and process member variables.

Calling Member Functions


After creating your objects, you will be able to call member functions related to that
object. One member function will be able to process member variable of related object
only.

Following example shows how to set title and prices for the three books by calling
member functions.

$physics->setTitle( "Physics for High School" );

$chemistry->setTitle( "Advanced Chemistry" );

$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );

$chemistry->setPrice( 15 );

$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example −

$physics->getTitle();

$chemistry->getTitle();

_____________________________________________________________________________
24 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$maths->getTitle();

$physics->getPrice();

$chemistry->getPrice();

$maths->getPrice();

This will produce the following result −

Physics for High School

Advanced Chemistry

Algebra

10

15

Constructor Functions
Constructor Functions are special type of functions which are called automatically
whenever an object is created. So we take full advantage of this behaviour, by
initializing many things through constructor functions.

PHP provides a special function called __construct() to define a constructor. You can
pass as many arguments as you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price
and title for the book at the time of object creation.

function __construct( $par1, $par2 ) {

$this->title = $par1;

$this->price = $par2;

Now we don't need to call set function separately to set price and title. We can
initialize these two member variables at the time of object creation only. Check
following example below −

$physics = new Books( "Physics for High School", 10 );

$maths = new Books ( "Advanced Chemistry", 15 );

$chemistry = new Books ("Algebra", 7 );


_____________________________________________________________________________
25 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
/* Get those set values */

$physics->getTitle();

$chemistry->getTitle();

$maths->getTitle();

$physics->getPrice();

$chemistry->getPrice();

$maths->getPrice();

This will produce the following result −

Physics for High School

Advanced Chemistry

Algebra

10

15

Destructor
Like a constructor function you can define a destructor function using function
__destruct(). You can release all the resources with-in a destructor.

Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the
extend clause. The syntax is as follows −

class Child extends Parent {

<definition body>

The effect of inheritance is that the child class (or subclass or derived class) has the
following characteristics −

Automatically it has all the member variable declarations of the parent class.

_____________________________________________________________________________
26 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Automatically it has all the same member functions as the parent, which (by default)
will work the same way as those functions do in the parent.

Following examples inherit Books class and adds more functionality based on the
requirement.

class Novel extends Books {

var $publisher;

function setPublisher($par){

$this->publisher = $par;

function getPublisher(){

echo $this->publisher. "<br />";

Now apart from inherited functions, class Novel keeps two additional member
functions.

Function Overriding
Function definitions in child classes override definitions with the same name in parent
classes. In a child class, we can modify the definition of a function inherited from
parent class.

In the following example getPrice and getTitle functions are overridden to return some
values.

function getPrice() {

echo $this->price . "<br/>";

return $this->price;

function getTitle(){

echo $this->title . "<br/>";

return $this->title;

}
_____________________________________________________________________________
27 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to
say, they may be accessed in three possible situations −

From outside the class in which it is declared

From within the class in which it is declared

From within another class that implement the class in which it is declared

Till now we have seen all members as public members. If you wish to limit the
accessibility of the members of a class then you define class members as private or
protected.

Private members
By designating a member private, you limit its accessibility to the class in which it is
declared. The private member cannot be referred to from classes that inherit the class
in which it is declared and cannot be accessed from outside the class.

A class member can be made private by using private keyword infront of the member.

class MyClass {

private $car = "skoda";

$driver = "SRK";

function __construct($par) {

// Statements here run every time

// an instance of the class

// is created.

function myPublicFunction() {

return("I'm visible!");

private function myPrivateFunction() {

return("I'm not visible outside!");

}
_____________________________________________________________________________
28 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
When MyClass class is inherited by another class using extends, myPublicFunction()
will be visible, as will $driver. The extending class will not have any awareness of or
access to myPrivateFunction and $car, because they are declared private.

Protected members
A protected property or method is accessible in the class in which it is declared, as
well as in classes that extend that class. Protected members are not available outside
of those two kinds of classes. A class member can be made protected by using
protected keyword in front of the member.

Here is different version of MyClass −

class MyClass {

protected $car = "skoda";

$driver = "SRK";

function __construct($par) {

// Statements here run every time

// an instance of the class

// is created.

function myPublicFunction() {

return("I'm visible!");

protected function myPrivateFunction() {

return("I'm visible in child class!");

Interfaces

Interfaces are defined to provide a common function names to the implementers.


Different implementors can implement those interfaces according to their
requirements. You can say, interfaces are skeletons which are implemented by
developers.

_____________________________________________________________________________
29 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
As of PHP5, it is possible to define an interface, like this −

interface Mail {

public function sendMail();

Then, if another class implemented that interface, like this −

class Report implements Mail {

// sendMail() Definition goes here

Constants
A constant is somewhat like a variable, in that it holds a value, but is really more like
a function because a constant is immutable. Once you declare a constant, it does not
change.

Declaring one constant is easy, as is done in this version of MyClass −

class MyClass {

const requiredMargin = 1.7;

function __construct($incomingValue) {

// Statements here run every time

// an instance of the class

// is created.

In this class, requiredMargin is a constant. It is declared with the keyword const, and
under no circumstances can it be changed to anything other than 1.7. Note that the
constant's name does not have a leading $, as variable names do.

Abstract Classes
An abstract class is one that cannot be instantiated, only inherited. You declare an
abstract class with the keyword abstract, like this −

_____________________________________________________________________________
30 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
When inheriting from an abstract class, all methods marked abstract in the parent's
class declaration must be defined by the child; additionally, these methods must be
defined with the same visibility.

abstract class MyAbstractClass {

abstract function myAbstractFunction() {

Note that function definitions inside an abstract class must also be preceded by the
keyword abstract. It is not legal to have abstract function definitions inside a non-
abstract class.

Static Keyword
Declaring class members or methods as static makes them accessible without needing
an instantiation of the class. A member declared as static cannot be accessed with an
instantiated class object (though a static method can).

Try out following example −

<?php

class Foo {

public static $my_static = 'foo';

public function staticValue() {

return self::$my_static;

print Foo::$my_static . "\n";

$foo = new Foo();

print $foo->staticValue() . "\n";

?>

_____________________________________________________________________________
31 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is being defined final
then it cannot be extended.

Following example results in Fatal error: Cannot override final method


BaseClass::moreTesting()

<?php

class BaseClass {

public function test() {

echo "BaseClass::test() called<br>";

final public function moreTesting() {

echo "BaseClass::moreTesting() called<br>";

class ChildClass extends BaseClass {

public function moreTesting() {

echo "ChildClass::moreTesting() called<br>";

?>

Calling parent constructors

Instead of writing an entirely new constructor for the subclass, let's write it by calling
the parent's constructor explicitly and then doing whatever is necessary in addition for
instantiation of the subclass. Here's a simple example −

class Name {

var $_firstName;

var $_lastName;
_____________________________________________________________________________
32 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
function Name($first_name, $last_name) {

$this->_firstName = $first_name;

$this->_lastName = $last_name;

function toString() {

return($this->_lastName .", " .$this->_firstName);

class NameSub1 extends Name {

var $_middleInitial;

function NameSub1($first_name, $middle_initial, $last_name) {

Name::Name($first_name, $last_name);

$this->_middleInitial = $middle_initial;

function toString() {

return(Name::toString() . " " . $this->_middleInitial);

In this example, we have a parent class (Name), which has a two-argument


constructor, and a subclass (NameSub1), which has a three-argument constructor.
The constructor of NameSub1 functions by calling its parent constructor explicitly
using the:: syntax (passing two of its arguments along) and then setting an additional
field. Similarly, NameSub1 defines its non constructor toString() function in terms of
the parent function that it overrides.

NOTE − A constructor can be defined with the same name as the name of a class. It is
defined in above example.

_____________________________________________________________________________
33 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Benefits in running PHP as a server side script
Advantages of Server-Side Scripting

Server-side scripting is defined as “web server technology in which the user’s request
is fulfilled by running a script directly on a web server to generate dynamic web
pages.” In simpler terms, a server-side script runs on the server rather than your
computer. When you visit a website, the script will create the web page on the fly
(dynamically).

Dynamic websites have become very popular because they are so much easier to
maintain. Rather than having to edit HTML pages on a local computer and then
upload them back to the server via FTP, websites with server-side scripts can usually
be updated right on the server. The files themselves do not change, as they only
contain the scripts. Instead, the information is stored in an SQL or flat file database.

PHP is a popular server-side scripting language. Other popular languages in this


category are Perl, ASP, JSP, Ruby, ColdFusion, and Python.

Some of the advantages of server-side scripting are:

1. It does not require the user to download plugins like Java or Flash (client-side
scripting).

2. You can create a single website template for the entire website. Each new dynamic
page you create will automatically use it.

3. You can configure a site to use a content management system, which simplifies the
editing, publishing, adding of images, and creation of web applications. Many apps
are often available in the form of extensions or add-ons.

4. Load times are generally faster than client-side scripting.

5. Your scripts are hidden from view. Users only see the HTML output, even when
they view the source.

Installing a web server


To start using PHP, you can:

Find a web host with PHP and MySQL support

Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support

If your server has activated support for PHP you do not need to do anything.

_____________________________________________________________________________
34 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Just create some .php files, place them in your web directory, and the server will
automatically parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support.
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:
install a web server
install PHP
install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php

You can follow these detailed instructions while installing PHP for use in your
computer.

Internet information server and IIS installation


To install Internet Information Services

Close all applications that are currently running on your computer.

In Control Panel, double-click Add or Remove Programs.

In the left pane, click Add/Remove Windows Components. The Windows Components
Wizard will launch.

Select Internet Information Services, and then click Next. If the check box is already
selected, IIS is already installed on your computer.

For some server operating systems, IIS may be a component of the Application Server
selection. If this is the case for your operating system, select Application Server, and
then click Next.

Activity-1: (Answer the following questions)


1. What is PHP, explain?
2. Advantages of PHP.
3. Is PHP a server side or client side scripting language?
4. Explain object orient concepts.

Activity-2:
Perform the below exercise till you are confident.

1. Write a PHP script to get the client IP address.

_____________________________________________________________________________
35 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Solution: PHP Code

<?php
//whether ip is from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from remote address
else
{
$ip_address = $_SERVER['REMOTE_ADDR'];
}
echo $ip_address;
?>

2. Write a PHP script, which changes the color of the first character of a word.

Solution: PHP Code

<?php
$text = 'PHP Training';
$text = preg_replace('/(\b[a-z])/i','<span
style="color:red;">\1</span>',$text);
echo $text;
?>

3. Write a PHP script to redirect a user to a different page.

Solution: PHP Code

<?php
header('Location: http://www.w3resource.com/');
?>

_____________________________________________________________________________
36 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
UNIT II
The basics of PHP, data types

PHP provides eight types of values, or data types. Four are scalar (single-value) types:
integers, floating-point numbers, strings, and booleans. Two are compound (collection)
types: arrays and objects. The remaining two are special types: resource and NULL.

Integers
Integers are whole numbers, like 1, 12, and 256. The range of acceptable values varies
according to the details of your platform but typically extends from –2,147,483,648 to
+2,147,483,647. Specifically, the range is equivalent to the range of the long data type
of your C compiler. Unfortunately, the C standard doesn’t specify what range that long
type should have, so on some systems you might see a different integer range. Integer
literals can be written in decimal, octal, or hexadecimal. Decimal values are
represented by a sequence of digits, without leading zeros. The sequence may begin
with a plus (+) or minus (–) sign. If there is no sign, positive is assumed.

Examples of decimal integers include the following:

1998

-641

+33

Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal
numbers, octal numbers can be prefixed with a plus or minus. Here are some example
octal values and their equivalent decimal values:

0755 // decimal 493

+010 // decimal 8

Hexadecimal values begin with 0x, followed by a sequence of digits (0–9) or letters (A–
F). The letters can be upper- or lowercase but are usually written in capitals. Like
decimal and octal values, you can include a sign in hexadecimal numbers:

0xFF // decimal 255

0x10 // decimal 16

-0xDAD1 // decimal -56017

If you try to store a too-large integer in a variable, it will automatically be turned into a
floating-point number.

_____________________________________________________________________________
37 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Use the is_int( ) function (or its is_integer( ) alias) to test whether a value is an
integer:
if (is_int($x)) {
// $x is an integer

Floating-Point Numbers
Floating-point numbers (often referred to as real numbers) represent numeric values
with decimal digits. Like integers, their limits depend on your machine’s details. PHP
floating-point numbers are equivalent to the range of the double data type of your C
compiler. Usually, this allows numbers between 1.7E–308 and 1.7E+308 with 15
digits of accuracy. If you need more accuracy or a wider range of integer values, you
can use the BC or GMP extensions.

PHP recognizes floating-point numbers written in two different formats. There’s theone
we all use every day:

3.14

0.017

-7.1

but PHP also recognizes numbers in scientific notation:

0.314E1 // 0.314*101, or 3.14

17.0E-3 // 17.0*10-3, or 0.017

Floating-point values are only approximate representations of numbers. For example,


on many systems 3.5 is actually represented as 3.4999999999. This means you must
take care to avoid writing code that assumes floating-point numbers are represented
completely accurately, such as directly comparing two floating-point values using ==.
The normal approach is to compare to several decimal places:
if (int($a * 1000) == int($b * 1000)) {
// numbers equal to three decimal places
Use the is_float( ) function (or its is_real( ) alias) to test whether a value is a floating
point number:
if (is_float($x)) {

// $x is a floating-point number

}
_____________________________________________________________________________
38 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Strings
Because strings are so common in web applications, PHP includes core-level support
for creating and manipulating strings. A string is a sequence of characters of arbitrary
length. String literals are delimited by either single or double quotes:

'big dog'

"fat hog"

Variables are expanded within double quotes, while within single quotes they are not:

$name = "Guido";

echo "Hi, $name\n";

echo 'Hi, $name';

Hi, Guido

Hi, $name

Double quotes also support a variety of string escapes, as listed in Table 2-1.

Table 2-1. Escape sequences in double-quoted strings

_____________________________________________________________________________
39 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
A single-quoted string only recognizes \\ to get a literal backslash and \' to get a
literal single quote:

$dos_path = 'C:\\WINDOWS\\SYSTEM';

$publisher = 'Tim O\'Reilly';

echo "$dos_path $publisher\n";

C:\WINDOWS\SYSTEM Tim O'Reilly

To test whether two strings are equal, use the == comparison operator:

if ($a == $b) { echo "a and b are equal" }

Use the is_string( ) function to test whether a value is a string:

if (is_string($x)) {

// $x is a string

PHP provides operators and functions to compare, disassemble, assemble, search,


replace, and trim strings, as well as a host of specialized string functions for working
with HTTP, HTML, and SQL encodings.

Booleans
A boolean value represents a “truth value”—it says whether something is true or not.
Like most programming languages, PHP defines some values as true and others as
false. Truth and falseness determine the outcome of conditional code such as:

if ($alive) { ... }

In PHP, the following values are false:

• The keyword false

• The integer 0

• The floating-point value 0.0

• The empty string ("") and the string "0"

• An array with zero elements

• An object with no values or functions

• The NULL value

_____________________________________________________________________________
40 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Any value that is not false is true, including all resource values (which are described
later, in the “Resources” section).

PHP provides true and false keywords for clarity:

$x = 5; // $x has a true value

$x = true; // clearer way to write it

$y = ""; // $y has a false value

$y = false; // clearer way to write it

Use the is_bool( ) function to test whether a value is a boolean:

if (is_bool($x)) {

// $x is a boolean

Arrays
An array holds a group of values, which you can identify by position (a number, with
zero being the first position) or some identifying name (a string):

$person[0] = "Edison";

$person[1] = "Wankel";

$person[2] = "Crapper";

$creator['Light bulb'] = "Edison";

$creator['Rotary Engine'] = "Wankel";

$creator['Toilet'] = "Crapper";

The array( ) construct creates an array:

$person = array('Edison', 'Wankel', 'Crapper');

$creator = array('Light bulb' => 'Edison',

'Rotary Engine' => 'Wankel',

'Toilet' => 'Crapper');

There are several ways to loop across arrays, but the most common is a foreach loop:

foreach ($person as $name) {

_____________________________________________________________________________
41 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "Hello, $name\n";

foreach ($creator as $invention => $inventor) {

echo "$inventor created the $invention\n";

Hello, Edison

Hello, Wankel

Hello, Crapper

Edison created the Light bulb

Wankel created the Rotary Engine

Crapper created the Toilet

You can sort the elements of an array with the various sort functions:

sort($person);

// $person is now array('Crapper', 'Edison', 'Wankel')

asort($creator);

// $creator is now array('Toilet' => 'Crapper',

// 'Light bulb' => 'Edison',

// 'Rotary Engine' => 'Wankel');

Use the is_array( ) function to test whether a value is an array:

if (is_array($x)) {

// $x is an array

There are functions for returning the number of items in the array, fetching every
value in the array, and much more.

_____________________________________________________________________________
42 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Objects
PHP supports object-oriented programming (OOP). OOP promotes clean modular
design, simplifies debugging and maintenance, and assists with code reuse. Classes
are the unit of object-oriented design. A class is a definition of a structure that
contains properties (variables) and methods (functions). Classes are defined with the
class keyword:

class Person {

var $name = '';

function name ($newname = NULL) {

if (! is_null($newname)) {

$this->name = $newname;
}
return $this->name;
}
}
Once a class is defined, any number of objects can be made from it with the new
keyword, and the properties and methods can be accessed with the -> construct:
$ed = new Person;
$ed->name('Edison');
printf("Hello, %s\n", $ed->name);

$tc = new Person;

$tc->name('Crapper');

printf("Look out below %s\n", $tc->name);

Hello, Edison

Look out below Crapper

Use the is_object( ) function to test whether a value is an object:

if (is_object($x)) {

// $x is an object

_____________________________________________________________________________
43 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Resources
Many modules provide several functions for dealing with the outside world. For
example, every database extension has at least a function to connect to the database,
a function to send a query to the database, and a function to close the connection to
the database. Because you can have multiple database connections open at once, the
connect function gives you something by which to identify that connection when you
call the query and close functions: a resource.

Resources are really integers under the surface. Their main benefit is that they’re
garbage collected when no longer in use. When the last reference to a resource value
goes away, the extension that created the resource is called to free any memory, close
any connection, etc. for that resource:

$res = database_connect( ); // fictitious function

database_query($res);

$res = "boo"; // database connection automatically closed

The benefit of this automatic cleanup is best seen within functions, when the resource
is assigned to a local variable. When the function ends, the variable’s value is
reclaimed by PHP:

function search ( ) {

$res = database_connect( );

$database_query($res);

When there are no more references to the resource, it’s automatically shut down. That
said, most extensions provide a specific shutdown or close function, and it’s
considered good style to call that function explicitly when needed rather than to rely
on variable scoping to trigger resource cleanup. Use the is_resource( ) function to test
whether a value is a resource:

if (is_resource($x)) {

// $x is a resource

NULL
There’s only one value of the NULL data type. That value is available through the

case-insensitive keyword NULL. The NULL value represents a variable that has no
value
_____________________________________________________________________________
44 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
(similar to Perl’s undef or Python’s None):

$aleph = "beta";

$aleph = null; // variable's value is gone

$aleph = Null; // same

$aleph = NULL; // same

Use the is_null( ) function to test whether a value is NULL—for instance, to see

whether a variable has a value:

if (is_null($x)) {

// $x is NULL

Variables
Variables in PHP are identifiers prefixed with a dollar sign ($). For example:

$name

$Age

$_debugging

$MAXIMUM_IMPACT

A variable may hold a value of any type. There is no compile- or runtime type checking
on variables. You can replace a variable’s value with another of a different type:

$what = "Fred";

$what = 35;

$what = array('Fred', '35', 'Wilma');

There is no explicit syntax for declaring variables in PHP. The first time the value of a
variable is set, the variable is created. In other words, setting a variable functions as a
declaration. For example, this is a valid complete PHP program:

$day = 60 * 60 * 24;

echo "There are $day seconds in a day.\n";

_____________________________________________________________________________
45 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
There are 86400 seconds in a day.

A variable whose value has not been set behaves like the NULL value:

if ($uninitialized_variable === NULL) {

echo "Yes!";

Yes

Variable Variables
You can reference the value of a variable whose name is stored in another variable.

For example:

$foo = 'bar';

$$foo = 'baz';

After the second statement executes, the variable $bar has the value "baz".

Variable References

In PHP, references are how you create variable aliases. To make $black an alias for the
variable $white, use:

$black =& $white;

The old value of $black is lost. Instead, $black is now another name for the value

that is stored in $white:

$big_long_variable_name = "PHP";

$short =& $big_long_variable_name;

$big_long_variable_name .= " rocks!";

print "\$short is $short\n";

print "Long is $big_long_variable_name\n";

$short is PHP rocks!

Long is PHP rocks!

$short = "Programming $short";

_____________________________________________________________________________
46 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
print "\$short is $short\n";

print "Long is $big_long_variable_name\n";

$short is Programming PHP rocks!

Long is Programming PHP rocks!

After the assignment, the two variables are alternate names for the same value.

Unsetting a variable that is aliased does not affect other names for that variable’s

value, though:

$white = "snow";

$black =& $white;

unset($white);

print $black;

snow

Functions can return values by reference (for example, to avoid copying large strings

or arrays, as discussed in Chapter 3):

function &ret_ref() { // note the &

$var = "PHP";

return $var;

$v =& ret_ref(); // note the &

Variable Scope
The scope of a variable, which is controlled by the location of the variable’s
declaration, determines those parts of the program that can access it. There are four
types of variable scope in PHP: local, global, static, and function parameters.

Local scope
A variable declared in a function is local to that function. That is, it is visible only to
code in that function (including nested function definitions); it is not accessible
outside the function. In addition, by default, variables defined outside a function
(called global variables) are not accessible inside the function. For example, here’s a
function that updates a local variable instead of a global variable:

_____________________________________________________________________________
47 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
function update_counter ( ) {

$counter++;

$counter = 10;

update_counter( );

echo $counter;

10

The $counter inside the function is local to that function, because we haven't said
otherwise. The function increments its private $counter, whose value is thrown away
when the subroutine ends.

The global $counter remains set at 10.

Only functions can provide local scope. Unlike in other languages, in PHP you can't
create a variable whose scope is a loop, conditional branch, or other type of block.

Global scope
Variables declared outside a function are global. That is, they can be accessed from
any part of the program. However, by default, they are not available inside functions.
To allow a function to access a global variable, you can use the global keyword inside
the function to declare the variable within the function. Here’s how we can rewrite the
update_counter( ) function to allow it to access the global $counter variable:

function update_counter ( ) {

global $counter;

$counter++;

$counter = 10;

update_counter( );

echo $counter;

11

A more cumbersome way to update the global variable is to use PHP’s $GLOBALS
array instead of accessing the variable directly:

_____________________________________________________________________________
48 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
function update_counter ( ) {

$GLOBALS[counter]++;

$counter = 10;

update_counter( );

echo $counter;

11

Static variables

A static variable retains its value between calls to a function but is visible only within
that function. You declare a variable static with the static keyword. For example:

function update_counter ( ) {

static $counter = 0;

$counter++;

echo "Static counter is now $counter\n";

$counter = 10;

update_counter( );

update_counter( );

echo "Global counter is $counter\n";

Static counter is now 1

Static counter is now 2

Global counter is 10

Function parameters

As we’ll discuss in more detail in Chapter 3, a function definition can have named
parameters:

function greet ($name) {

_____________________________________________________________________________
49 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "Hello, $name\n";

greet("Janet");

Hello, Janet

Function parameters are local, meaning that they are available only inside their
functions.

In this case, $name is inaccessible from outside greet( ).

Constants
A constant is an identifier for a simple value; only scalar values—boolean, integer,
double, and string—can be constants. Once set, the value of a constant cannot
change. Constants are referred to by their identifiers and are set using the define( )

function:

define('PUBLISHER', "O'Reilly & Associates");

echo PUBLISHER;

Operators
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9.
Here 4 and 5 are called operands and + is called operator. PHP language supports
following type of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

Let’s have a look on all operators one by one.

Arithmetic Operators
There are following arithmetic operators supported by PHP language:

Assume variable A holds 10 and variable B holds 20 then:

_____________________________________________________________________________
50 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Example

Try the following example to understand all the arithmetic operators. Copy and paste following
PHP program in test.php file and keep it in your PHP Server's document root and browse it
using any browser.

_____________________________________________________________________________
51 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

This will produce the following result:

Addition Operation Result: 62


Subtraction Operation Result: 22
Multiplication Operation Result: 840
Division Operation Result: 2.1
Modulus Operation Result: 2
Increment Operation Result: 42
Decrement Operation Result: 43

_____________________________________________________________________________
52 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Comparison Operators
There are following comparison operators supported by PHP language Assume variable
A holds 10 and variable B holds 20 then:

Example
Try the following example to understand all the comparison operators. Copy and paste
following PHP program in test.php file and keep it in your PHP Server's document root
and browse it using any browser.
<html>
<head><title>Comparison Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ){
echo "TEST1 : a is equal to b<br/>";
}else{
echo "TEST1 : a is not equal to b<br/>";

_____________________________________________________________________________
53 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
}
if( $a > $b ){
echo "TEST2 : a is greater than b<br/>";
}else{
echo "TEST2 : a is not greater than b<br/>";
}
if( $a < $b ){
echo "TEST3 : a is less than b<br/>";
}else{
echo "TEST3 : a is not less than b<br/>";
}
if( $a != $b ){
echo "TEST4 : a is not equal to b<br/>";
}else{
echo "TEST4 : a is equal to b<br/>";
}
if( $a >= $b ){
echo "TEST5 : a is either greater than or equal to b<br/>";
}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";
}
if( $a <= $b ){
echo "TEST6 : a is either less than or equal to b<br/>";
}else{
echo "TEST6 : a is neither less than nor equal to b<br/>";
}
?>
</body>
</html>

This will produce the following result:

TEST1 : a is not equal to b


TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either greater than or equal to b
TEST6 : a is neither less than nor equal to b

Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:

_____________________________________________________________________________
54 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Example
Try the following example to understand all the logical operators. Copy and paste the
following PHP program in test.php file and keep it in your PHP Server's document root
and browse it using any browser.
<html>
<head><title>Logical Operators</title><head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ){
echo "TEST1 : Both a and b are true<br/>";
}else{
echo "TEST1 : Either a or b is false<br/>";
}
if( $a and $b ){
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
}
if( $a || $b ){

_____________________________________________________________________________
55 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "TEST3 : Either a or b is true<br/>";
}else{
echo "TEST3 : Both a and b are false<br/>";
}
if( $a or $b ){
echo "TEST4 : Either a or b is true<br/>";
}else{
echo "TEST4 : Both a and b are false<br/>";
}
$a = 10;
$b = 20;
if( $a ){
echo "TEST5 : a is true <br/>";
}else{
echo "TEST5 : a is false<br/>";
}
if( $b ){
echo "TEST6 : b is true <br/>";
}else{
echo "TEST6 : b is false<br/>";
}
if( !$a ){
echo "TEST7 : a is true <br/>";
}else{
echo "TEST7 : a is false<br/>";
}
if( !$b ){
echo "TEST8 : b is true <br/>";
}else{
echo "TEST8 : b is false<br/>";
}
?>
</body>
</html>
This will produce the following result:
TEST1 : Either a or b is false
TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
_____________________________________________________________________________
56 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Assignment Operators
PHP supports the following assignment operators:

Example
Try the following example to understand all the assignment operators. Copy and paste
the following PHP program in test.php file and keep it in your PHP Server's document
root and browse it using any browser.
<html>
<head><title>Assignment Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b; /* Assignment operator */

_____________________________________________________________________________
57 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "Addition Operation Result: $c <br/>";
$c += $a; /* c value was 42 + 20 = 62 */
echo "Add AND Assignment Operation Result: $c <br/>";
$c -= $a; /* c value was 42 + 20 + 42 = 104 */
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a; /* c value was 104 - 42 = 62 */
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a; /* c value was 62 * 42 = 2604 */
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a; /* c value was 2604/42 = 62*/
echo "Modulus AND Assignment Operation Result: $c <br/>";
?>
</body>
</html>

This will produce the following result:


Addition Operation Result: 62
Add AND Assignment Operation Result: 104
Subtract AND Assignment Operation Result: 62
Multiply AND Assignment Operation Result: 2604
Division AND Assignment Operation Result: 62
Modulus AND Assignment Operation Result: 20

Conditional Operator
There is one more operator called the conditional operator. It first evaluates an
expression for a true or false value and then executes one of the two given statements
depending upon the result of the evaluation.

Try the following example to understand the conditional operator. Copy and paste the
following PHP program in test.php file and keep it in your PHP Server's document root
and browse it using any browser.
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otherwise b */
_____________________________________________________________________________
58 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>
This will produce the following result:
TEST1 : Value of result is 20
TEST2 : Value of result is 10

Operators Categories
All the operators we have discussed above can be categorized into following categories:
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression. Assignment operators, which assign a value to a variable.

Precedence of PHP Operators


Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the
addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.

_____________________________________________________________________________
59 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Arrays
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100
variables it’s easy to define an array of 100 length.

There are three different kinds of arrays and each array value is accessed using an ID
c which is called array index.

Numeric array - An array with a numeric index. Values are stored and accessed in
linear fashion Associative array - An array with strings as index. This stores element
values in association with key values rather than in a strict linear index order.

Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices.

_____________________________________________________________________________
60 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Numeric Array
These arrays can store numbers, strings and any object but their index will be
represented by numbers. By default, the array index starts from zero.

Example

The following example demonstrates how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in
function reference.

<html>

<body>

<?php

/* First method to create array. */

$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value )

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

/* Second method to create array. */

$numbers[0] = "one";

$numbers[1] = "two";

$numbers[2] = "three";

$numbers[3] = "four";

$numbers[4] = "five";

foreach( $numbers as $value )

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

?>

_____________________________________________________________________________
61 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
</body>

</html>

This will produce the following result:

Value is 1

Value is 2

Value is 3

Value is 4

Value is 5

Value is one

Value is two

Value is three

Value is four

Value is five

Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but
they are different in terms of their index. Associative array will have their index as
string so that 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.

NOTE: Don't keep associative array inside double quote while printing, otherwise it
would not return any value.

Example

<html>

<body>

<?php

/* First method to associate create array. */

_____________________________________________________________________________
62 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$salaries = array(

"mohammad" => 2000,

"qadir" => 1000,

"zara" => 500

);

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

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

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

/* Second method to create array. */

$salaries['mohammad'] = "high";

$salaries['qadir'] = "medium";

$salaries['zara'] = "low";

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

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

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

?>

</body>

</html>

This will produce following result:

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


_____________________________________________________________________________
63 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And
each element in the sub-array can be an array, and so on. Values in the multi-
dimensional array are accessed using multiple indexes.

Example

In this example, we create a two dimensional array to store marks of three students in
three subjects:

This example is an associative array, you can create numeric array in the same
fashion.

<html>

<body>

<?php

$marks = array(

"mohammad" => array

"physics" => 35,

"maths" => 30,

"chemistry" => 39

),

"qadir" => array

"physics" => 30,

"maths" => 32,

"chemistry" => 29

),

"zara" => array

"physics" => 31,


_____________________________________________________________________________
64 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
"maths" => 22,

"chemistry" => 39

);

/* Accessing multi-dimensional array values */

echo "Marks for mohammad in physics : " ;

echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";

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

echo "Marks for zara in chemistry : " ;

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

?>

</body>

</html>

This will produce the following result:

Marks for mohammad in physics : 35

Marks for qadir in maths : 32

Marks for zara in chemistry : 39

Conditional statements (if statement Executing Multiple Statements


else if clause and switch statement)
Theif, elseif ...else and switch statements are used to take decision based on the
different condition.

You can use conditional statements in your code to make your decisions. PHP
supports following three decision making statements:

if...else statement - use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true.

_____________________________________________________________________________
65 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
elseif statement - is used with the if...else statement to execute a set of code if one of
several condition are true

Switch statement - is used if you want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long blocks
of if..elseif..else code.

The If...Else Statement


If you want to execute some code if a condition is true and another code if a condition
is false, use the if....else statement.

Syntax

if (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":

<html>

<body>

<?php

$d=date("D");

if ($d=="Fri")

echo "Have a nice weekend!";

else

echo "Have a nice day!";

?>

</body>

</html>

If more than one line should be executed in case a condition is true/false, then the
lines should be enclosed within curly braces:
_____________________________________________________________________________
66 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
<html>

<body>

<?php

$d=date("D");

if ($d=="Fri")

echo "Hello!<br />";

echo "Have a nice weekend!";

echo "See you on Monday!";

?>

</body>

</html>

The ElseIf Statement


If you want to execute some code if one of the several conditions is true, then use the
elseif statement.

Syntax

if (condition)

code to be executed if condition is true;

elseif (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

_____________________________________________________________________________
67 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Example

The following example will output "Have a nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have
a nice day!":

<html>

<body>

<?php

$d=date("D");

if ($d=="Fri")

echo "Have a nice weekend!";

elseif ($d=="Sun")

echo "Have a nice Sunday!";

else

echo "Have a nice day!";

?>

</body>

</html>

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch
statement.

The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression)

case label1:

code to be executed if expression = label1;

break;

_____________________________________________________________________________
68 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
case label2:

code to be executed if expression = label2;

break;

default:

code to be executed

if expression is different

from both label1 and label2;

Example

The switch statement works in an unusual way. First it evaluates given expression
then seeks a label to match the resulting value. If a matching value is found, then the
code associated with the matching label will be executed. If none of the labels match,
then the statement will execute any specified default code.

<html>

<body>

<?php

$d=date("D");

switch ($d)

case "Mon":

echo "Today is Monday";

break;

case "Tue":

echo "Today is Tuesday";

break;

case "Wed":

echo "Today is Wednesday";

_____________________________________________________________________________
69 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
break;

case "Thu":

echo "Today is Thursday";

break;

case "Fri":

echo "Today is Friday";

break;

case "Sat":

echo "Today is Saturday";

break;

case "Sun":

echo "Today is Sunday";

break;

default:

echo "Wonder which day is this ?";

?>

</body>

</html>

Iterations (for loop while loop controlling an array using a while loop
do while statement for each loop and special loop key words)
Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types.

for - loops through a block of code a specified number of times.

while - loops through a block of code if and as long as a specified condition is true.

do...while - loops through a block of code once, and then repeats the loop as long as a
special condition is true.

_____________________________________________________________________________
70 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
foreach - loops through a block of code for each element in an array.

We will discuss about continue and break keywords used to control the loops
execution.

The for loop statement


The for loop statement is used when you know how many times you want to execute a
statement or a block of statements.

Syntax

for (initialization; condition; increment)

code to be executed;

The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to
name it $i.

Example

The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop:

<html>

<body>

<?php

$a = 0;

$b = 0;

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

$a += 10;

$b += 5;

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

_____________________________________________________________________________
71 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
?>

</body>

</html>

This will produce the following result:

At the end of the loop a=50 and b=25

The while loop statement


The while statement will execute a block of code if and as long as a test expression is
true.

If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until
the test expression is found to be false.

Syntax

while (condition)
{
code to be executed;
}

Example

This example decrements a variable value on each iteration of the loop and the
counter increments until it reaches 10 when the evaluation becomes false and the loop
ends.

<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>

_____________________________________________________________________________
72 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
This will produce the following result:

Loop stopped at i = 10 and num = 40

The do...while loop statement


The do...while statement will execute a block of code at least once - it then will repeat
the loop as long as a condition is true.

Syntax

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

Example

The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10:

<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>

This will produce the following result:

Loop stopped at i = 10

The foreach loop statement


The foreach statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one and
in the next pass next element will be processed.

_____________________________________________________________________________
73 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Syntax

foreach (array as value)


{
code to be executed;
}

Example

Try out the following example to list out the values of an array.

<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>

This will produce the following result:

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement


The PHP break keyword is used to terminate the execution of a loop prematurely.

The break statement is situated inside the statement block. If gives you full control
and whenever you want to exit from the loop you can come out. After coming out of a
loop immediate statement to the loop will be executed.

Example

In the following example, the condition test becomes true when the counter value
reaches 3 and loop terminates.

<html>
<body>
<?php
_____________________________________________________________________________
74 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>

This will produce the following result:

Loop stopped at i = 3

The continue statement


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

Just like the break statement the continue statement is situated inside the statement
block containing the code that the loop executes, preceded by a conditional test. For
the pass encountering continue statement, rest of the loop code is skipped and next
pass starts.

Example

In the following example loop prints the value of array but for which condition
becomes true it just skip the code and next value is printed.

<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>

_____________________________________________________________________________
75 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
This will produce the following result:

Value is 1
Value is 2
Value is 4
Value is 5

Activity-1: (Answer the following questions)


1. Explain Arrays in PHP.

2. Explain different Loops in PHP ex. For each, while etc.

3. What are the conditional statements in PHP?

Activity-2:
Perform the below exercise till you are confident.

1. Write a PHP script to delay the program execution for the given number of seconds.

Solution: PHP Code

<?php
// current time
echo date('h:i:s') . "\n";
// sleep for 5 seconds
sleep(5);
// wake up
echo date('h:i:s')."\n";
?>
2. $color = array('white', 'green', 'red', 'blue', 'black');
Write a script which will display the following string.
"The memory of that scene for me is like a frame of film forever frozen at that moment:
the red carpet, the green lawn, the white house, the leaden sky. The new president
and his first lady. - Richard M. Nixon" and the words 'red', 'green' and 'white' will come
from $color.

Solution: PHP Code


<?php
$color = array('white', 'green', 'red', 'blue', 'black');
echo "The memory of that scene for me is like a frame of film forever
frozen at that moment: the $color[2] carpet, the $color[1] lawn, the
$color[0] house, the leaden sky. The new president and his first lady. -
Richard M. Nixon"."\n";
?>
_____________________________________________________________________________
76 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

3. Write a PHP script to calculate and display average temperature, five lowest and
highest temperatures.
Recorded temperatures : 78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68,
62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73

Solution: PHP Code

<?php
$month_temp = "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73";
$temp_array = explode(',', $month_temp);
$tot_temp = 0;
$temp_array_length = count($temp_array);
foreach($temp_array as $temp)
{
$tot_temp += $temp;
}
$avg_high_temp = $tot_temp/$temp_array_length;
echo "Average Temperature is : ".$avg_high_temp."
";
sort($temp_array);
echo " List of seven lowest temperatures :";
for ($i=0; $i< 5; $i++)
{
echo $temp_array[$i].", ";
}
echo "List of seven highest temperatures :";
for ($i=($temp_array_length-5); $i< ($temp_array_length); $i++)
{
echo $temp_array[$i].", ";
}
?>

_____________________________________________________________________________
77 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
UNIT III
Functions
A function is a named block of code that performs a specific task, possibly acting upon
a set of values given to it, or parameters, and possibly returning a single value.
Functions save on compile time—no matter how many times you call them, functions
are compiled only once for the page. They also improve reliability by allowing you to fix
any bugs in one place, rather than everywhere you perform a task, and they improve
readability by isolating code that performs specific tasks. This unit introduces the
syntax of function calls and function definitions and discusses how to manage
variables in functions and pass values to functions (including pass-by-value and pass-
by-reference). It also covers variable functions and anonymous functions.

Calling a Function
Functions in a PHP program can be either built-in (or, by being in an extension,
effectively built-in) or user-defined. Regardless of their source, all functions are
evaluated in the same way:

$some_value = function_name( [ parameter, ... ] );

The number of parameters a function requires differs from function to function (and,
as we 'l see later, may even vary for the same function). The parameters supplied to
the function may be any valid expression and should be in the specific order expected
by the function. A function’s documentation will tell you what parameters the function
expects and what values you can expect to be returned.

Here are some examples of functions:

// strlen( ) is a built-in function that returns the length of a string

$length = strlen("PHP"); // $length is now 3

// sin() and asin( ) are the sine and arcsine math functions

$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0

// unlink( ) deletes a file

$result = unlink("functions.txt"); // false if unsuccessful

In the first example, we give an argument, "PHP", to the function strlen( ), which gives
us the number of characters in the string it’s given. In this case, it returns 3, which is
assigned to the variable $length. This is the simplest and most common way to use a
function.

_____________________________________________________________________________
78 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
The second example passes the result of asin(1) to the sin( ) function. Since the sine
and arcsine functions are reflexive, taking the sine of the arcsine of any value will
always return that same value.

In the final example, we give a filename to the unlink( ) function, which attempts to
delete the file. Like many functions, it returns false when it fails. This allows you to

use another built-in function, die( ), and the short-circuiting property of the logic

operators. Thus, this example might be rewritten as:

$result = unlink("functions.txt") or die("Operation failed!");

The unlink( ) function, unlike the other two examples, affects something outside of the
parameters given to it. In this case, it deletes a file from the file system. All such side
effects of a function should be carefully documented.

PHP has a huge array of functions already defined for you to use in your programs.
Everything from database access, to creating graphics, to reading and writing XML
files, to grabbing files from remote systems can be found in PHP’s many extensions.

Defining a Function
To define a function, use the following syntax:

function [&] function_name ( [ parameter [, ... ] ] )


{
statement list
}
The statement list can include HTML. You can declare a PHP function that doesn’t
contain any PHP code. For instance, the column( ) function simply gives a convenient
short name to HTML code that may be needed many times throughout the page:

<? function column( ) { ?>

</td><td>

<? } ?>

The function name can be any string that starts with a letter or underscore followed
by zero or more letters, underscores, and digits. Function names are case-insensitive;
that is, you can call the sin( ) function as sin(1), SIN(1), SiN(1), and so on, because all
these names refer to the same function.

Typically, functions return some value. To return a value from a function, use the
return statement: put return expr inside your function. When a return statement is
encountered during execution, control reverts to the calling statement, and the
evaluated results of expr will be returned as the value of the function. Although it can
_____________________________________________________________________________
79 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
make for messy code, you can actually include multiple return statements in a
function if it makes sense (for example, if you have a switch statement to determine

which of several values to return).

If you define your function with the optional ampersand before the name, the function

returns a reference to the returned data rather than a copy of the data.

Let’s take a look at a simple function. Example 3-1 takes two strings, concatenates

them, and then returns the result (in this case, we’ve created a slightly slower
equivalent

to the concatenation operator, but bear with us for the sake of example).

Example 3-1. String concatenation

function strcat($left, $right) {

$combined_string = $left . $right;

return $combined_string;

The function takes two arguments, $left and $right. Using the concatenation operator,

the function creates a combined string in the variable $combined_string. Finally,

in order to cause the function to have a value when it’s evaluated with our arguments,

we return the value $combined_string.

Because the return statement can accept any expression, even complex ones, we can

simplify the program as shown in Example 3-2.

Example3-2. String concatenation redux

function strcat($left, $right) {

return $left . $right;

_____________________________________________________________________________
80 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
If we put this function on a PHP page, we can call it from anywhere within the page.

Take a look at Example 3-3.

Example3-3. Using our concatenation function

<?php

function strcat($left, $right) {

return $left . $right;

$first = "This is a ";

$second = " complete sentence!";

echo strcat($first, $second);

?>

When this page is displayed, the full sentence is shown.

This function takes in an integer, doubles it, and returns the result:

function doubler($value) {

return $value << 1;

Once the function is defined, you can use it anywhere on the page. For example:

<?= 'A pair of 13s is ' . doubler(13); ?>

You can nest function declarations, but with limited effect. Nested declarations do

not limit the visibility of the inner-defined function, which may be called from
anywhere

in your program. The inner function does not automatically get the outer

function’s arguments. And, finally, the inner function cannot be called until the

outer function has been called.

function outer ($a) {

function inner ($b) {

_____________________________________________________________________________
81 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "there $b";

echo "$a, hello ";

outer("well");

inner("reader");

well, hello there reader

User defined functions


There are more than 1,000 in-built functions into the standard PHP distribution.
Besides these we can define functions as per our requirements. These are called 'User
Defined Function'.

Syntax

function function-name()

statement 1 :

statement 2 :

statement 3 :

......

Elements of a function

Function: A function declaration starts with the special word 'function'.

Name of the function:

The function name is defined by the user.

A valid function name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores.

Remember that function names are case-insensitive.

Opening and Closing curly braces ({ } )


_____________________________________________________________________________
82 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
The function body enclosed within a pair of braces which may contain variable names
and actual function code. The opening curly brace ( { ) indicates the beginning of the
function code and the closing curly ( } ) brace indicates the termination of the function.

Example: PHP function

Figure 3.1

Example: Functions within functions

_____________________________________________________________________________
83 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Figure 3.2

In the above example a function, function1() is declared and another function


function2() is declared within function1(). Now execute function1() first and then
function2() which print "Good Morning", executing function1() makes funtion2()
accessible. Therefore we cannot call function2() independently without calling
function1().

Functions with arguments

Creating PHP Function


It is very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the
PHP code should be put inside { and } braces as shown in the following example below:

_____________________________________________________________________________
84 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
This will display the following result:

PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters as you like. These parameters work like variables inside your function. Following
example takes two integer parameters, add them together and then print them.

This will display following result:

_____________________________________________________________________________
85 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Passing Arguments by Reference
It is possible to pass arguments to functions by reference. This means that a reference
to the variable is manipulated by the function rather than a copy of the variable's
value.

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

This will display the following result:

_____________________________________________________________________________
86 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
PHP Functions returning value
A function can return a value using the return statement in conjunction with a value or object.
Return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and adds them together and then returns their
sum to the calling program. Note that return keyword is used to return a value from a
function.

This will display the following result:

Built in functions( print() include() header() phpinfo() )


http://php.net/manual/en/functions.internal.php

PHP comes standard with many functions and constructs. There are also functions
that require specific PHP extensions compiled in, otherwise fatal "undefined function"
errors will appear. For example, to use image functions such as
_____________________________________________________________________________
87 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use
mysql_connect(), PHP must be compiled with MySQL support. There are many core
functions that are included in every version of PHP, such as the string and variable
functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are
loaded into PHP. Also note that many extensions are enabled by default and that the
PHP manual is split up by extension. See the configuration, installation, and
individual extension chapters, for information on how to set up PHP.

Reading and understanding a function's prototype is explained within the manual


section titled how to read a function definition. It's important to realize what a
function returns or if a function works directly on a passed in value. For example,
str_replace() will return the modified string while usort() works on the actual passed in
variable itself. Each manual page also has specific information for each function like
information on function parameters, behavior changes, return values for both success
and failure, and availability information. Knowing these important (yet often subtle)
differences is crucial for writing correct PHP code.

PHP print() Function


Definition and Usage

The print() function outputs one or more strings.

Note: The print() function is not actually a function, so you are not required to use
parentheses with it.

Tip: The print() function is slightly slower than echo().

Syntax

print(strings)

Parameter Description

strings Required. One or more strings to be sent to the output

Technical Details

Return Value: Always returns 1

PHP Version: 4+

_____________________________________________________________________________
88 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Example

Write the value of the string variable ($str) to the output:

include()
The include() function takes all the text in a specified file and copies it into the file that
uses the include function. If there is any problem in loading a file then the include()
function generates a warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file
menu.php with the following content.
<a href="http://www.tutorialspoint.com/index.htm">Home</a> -
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />

Now create as many pages as you like and include this file to create header. For
example now your test.php file can have following content.

_____________________________________________________________________________
89 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

http://www.w3schools.com/php/func_http_header.asp

PHP header() Function


Definition and Usage

The header() function sends a raw HTTP header to a client.

It is important to notice that header() must be called before any actual output
is sent (In PHP 4 and later, you can use output buffering to solve this problem):

<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>

_____________________________________________________________________________
90 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Syntax
header(string,replace,http_response_code)

Parameter Description

string Required. Specifies the header string to send

replace Optional. Indicates whether the header should replace


previous or add a second header. Default is TRUE (will
replace). FALSE (allows multiple headers of the same
type)

http_response_code Optional. Forces the HTTP response code to the


specified value (available in PHP 4.3 and higher)

Tips and Notes

Note: Since PHP 4.4 this function prevents more than one header to be sent
at once. This is a protection against header injection attacks.

Example 1

Prevent page caching:

<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
...
...
_____________________________________________________________________________
91 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Note: There are options that users may set to change the browser's default
caching settings. By sending the headers above, you should override any of
those settings and force the browser to not cache!

http://php.net/manual/en/function.phpinfo.php

phpinfo
phpinfo — Outputs information about PHP's configuration

Description ¶

bool phpinfo ([ int $what = INFO_ALL ] )

Outputs a large amount of information about the current state of PHP. This
includes information about PHP compilation options and extensions, the PHP
version, server information and environment (if compiled as a module), the PHP
environment, OS version information, paths, master and local values of
configuration options, HTTP headers, and the PHP License.

Because every system is setup differently, phpinfo() is commonly used to check


configuration settings and for available predefined variables on a given system.

phpinfo() is also a valuable debugging tool as it contains all EGPCS


(Environment, GET, POST, Cookie, Server) data.

Parameters ¶

what

The output may be customized by passing one or more of the following


constants bitwise values summed together in the optional what parameter. One
can also combine the respective constants or bitwise values together with the
or operator.

_____________________________________________________________________________
92 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
phpinfo() options

Name (constant) Value Description

INFO_GENERAL 1 The configuration line, php.ini location, build date, Web


Server, System and more.

INFO_CREDITS 2 PHP Credits. See also phpcredits().

INFO_CONFIGURATION 4 Current Local and Master values for PHP directives. See
also ini_get().

INFO_MODULES 8 Loaded modules and their respective settings. See


alsoget_loaded_extensions().

INFO_ENVIRONMENT 16 Environment Variable information that's also available


in $_ENV.

INFO_VARIABLES 32 Shows all predefined variables from EGPCS


(Environment, GET, POST, Cookie, Server).

INFO_LICENSE 64 PHP License information. See also the » license FAQ.

INFO_ALL -1 Shows all of the above.

Return Values ¶

Returns TRUE on success or FALSE on failure.

PHP server Variables

$_SERVER

$_SERVER is an array containing information such as headers, paths, and script locations.
The entries in this array are created by the web server. There is no guarantee that every web
server will provide any of these.

_____________________________________________________________________________
93 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Variable Description
$_SERVER['PHP_SELF'] The filename of the currently executing
script, relative to the document root
$_SERVER['argv'] Array of arguments passed to the script.
When the script is run on the command
line, this gives C-style access to the
command line parameters. When called via
the GET method, this will contain the
query string.
$_SERVER['argc'] Contains the number of command line
parameters passed to the script if run on
the command line.
$_SERVER['GATEWAY_INTERFACE'] What revision of the CGI specification the
server is using; i.e. 'CGI/1.1'.
$_SERVER['SERVER_ADDR'] The IP address of the server under which
the current script is executing.
$_SERVER['SERVER_NAME'] The name of the server host under which
the current script is executing. If the script
is running on a virtual host, this will be
the value defined for that virtual host.
$_SERVER['SERVER_SOFTWARE'] Server identification string, given in the
headers when responding to requests.
$_SERVER['SERVER_PROTOCOL'] Name and revision of the information
protocol via which the page was requested;
i.e. 'HTTP/1.0';
$_SERVER['REQUEST_METHOD'] Which request method was used to access
the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

$_SERVER['REQUEST_TIME'] The timestamp of the start of the request.


Available since PHP 5.1.0.
$_SERVER['QUERY_STRING'] The query string, if any, via which the
page was accessed.
$_SERVER['DOCUMENT_ROOT'] The document root directory under which
the current script is executing, as defined
in the server's configuration file.
$_SERVER['HTTP_ACCEPT'] Contents of the Accept: header from the
current request, if there is one.
$_SERVER['HTTP_ACCEPT_CHARSET'] Contents of the Accept-Charset: header
from the current request, if there is one.
Example: 'iso-8859-1,*,utf-8'.
$_SERVER['HTTP_ACCEPT_ENCODING'] Contents of the Accept-Encoding: header
from the current request, if there is one.
Example: 'gzip'.
$_SERVER['HTTP_ACCEPT_LANGUAGE'] Contents of the Accept-Language: header
from the current request, if there is one.
Example: 'en'.

_____________________________________________________________________________
94 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$_SERVER['HTTP_CONNECTION'] Contents of the Connection: header from
the current request, if there is one.
Example: 'Keep-Alive'.
$_SERVER['HTTP_HOST'] Contents of the Host: header from the
current request, if there is one.
$_SERVER['HTTP_REFERER'] The address of the page (if any) which
referred the user agent to the current
page.
$_SERVER['HTTP_USER_AGENT'] This is a string denoting the user agent
being which is accessing the page. A
typical example is: Mozilla/4.5 [en] (X11;
U; Linux 2.2.9 i586).
$_SERVER['HTTPS'] Set to a non-empty value if the script was
queried through the HTTPS protocol.

$_SERVER['REMOTE_ADDR'] The IP address from which the user is


viewing the current page.
$_SERVER['REMOTE_HOST'] The Host name from which the user is
viewing the current page. The reverse dns
lookup is based off the REMOTE_ADDR of
the user.
$_SERVER['REMOTE_PORT'] The port being used on the user's machine
to communicate with the web server.
$_SERVER['SCRIPT_FILENAME'] The absolute pathname of the currently
executing script.
$_SERVER['SERVER_ADMIN'] The value given to the SERVER_ADMIN (for
Apache) directive in the web server
configuration file.
$_SERVER['SERVER_PORT'] The port on the server machine being used
by the web server for communication. For
default setups, this will be '80'.
$_SERVER['SERVER_SIGNATURE'] String containing the server version and
virtual host name which are added to server-
generated pages, if enabled.
$_SERVER['PATH_TRANSLATED'] Filesystem based path to the current script.
$_SERVER['SCRIPT_NAME'] Contains the current script's path. This is
useful for pages which need to point to
themselves.
$_SERVER['REQUEST_URI'] The URI which was given in order to access
this page; for instance, '/index.html'.
$_SERVER['PHP_AUTH_DIGEST'] When running under Apache as module
doing Digest HTTP authentication this
variable is set to the 'Authorization' header
sent by the client.
$_SERVER['PHP_AUTH_USER'] When running under Apache or IIS (ISAPI on
PHP 5) as module doing HTTP
authentication this variable is set to the
username provided by the user.

_____________________________________________________________________________
95 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$_SERVER['PHP_AUTH_PW'] When running under Apache or IIS (ISAPI
on PHP 5) as module doing HTTP.
authentication this variable is set to the
password provided by the user.
$_SERVER['AUTH_TYPE'] When running under Apache as module
doing HTTP authenticated this variable is
set to the authentication type.

Working with date and time

Dates are so much part of everyday life that it becomes easy to work with them without
thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates
easy.

Getting the Time Stamp with time()


PHP's time() function gives you all the information that you need about the current date and
time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since
midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and
the number of seconds that have elapsed since then is referred to as a time stamp.

It will produce the following result:

948316201

This is something difficult to understand. But PHP offers excellent tools to convert a
time stamp into a form that humans are comfortable with.

Converting a Time Stamp with getdate()

The function getdate() optionally accepts a timestamp and returns an associative


array containing information about the date. If you omit the time stamp, it works with
the current time stamp as returned by time().

Following table lists the elements contained in the array returned by getdate().

_____________________________________________________________________________
96 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Now you have complete control over date and time. You can format this date and time in
whatever format you want.

_____________________________________________________________________________
97 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Example
Try out the following example.

It will produce the following result:

_____________________________________________________________________________
98 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Converting a Time Stamp with date()
The date() function returns a formatted string representing a date. You can exercise an
enormous amount of control over the format that date() returns with a string argument that
you must pass to it.

The date() optionally accepts a time stamp if omitted then current date and time will be used.
Any other data you include in the format string passed to date() will be included in the return
value.

_____________________________________________________________________________
99 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Following table lists the codes that a format string can contain:

_____________________________________________________________________________
100 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Example
Try out the following example.

It will produce following result:

Performing mathematical operations


http://php.net/manual/en/ref.math.php

 abs — Absolute value


 acos — Arc cosine
 acosh — Inverse hyperbolic cosine
 asin — Arc sine
 asinh — Inverse hyperbolic sine
 atan2 — Arc tangent of two variables
 atan — Arc tangent
 atanh — Inverse hyperbolic tangent
 base_convert — Convert a number between arbitrary bases
 bindec — Binary to decimal
 ceil — Round fractions up
 cos — Cosine
 cosh — Hyperbolic cosine
 decbin — Decimal to binary
 dechex — Decimal to hexadecimal
 decoct — Decimal to octal
 deg2rad — Converts the number in degrees to the radian equivalent
 exp — Calculates the exponent of e

_____________________________________________________________________________
101 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
 expm1 — Returns exp(number) - 1, computed in a way that is accurate even
when the value of number is close to zero
 floor — Round fractions down
 fmod — Returns the floating point remainder (modulo) of the division of the
arguments
 getrandmax — Show largest possible random value
 hexdec — Hexadecimal to decimal
 hypot — Calculate the length of the hypotenuse of a right-angle triangle
 intdiv — Integer division
 is_finite — Finds whether a value is a legal finite number
 is_infinite — Finds whether a value is infinite
 is_nan — Finds whether a value is not a number
 lcg_value — Combined linear congruential generator
 log10 — Base-10 logarithm
 log1p — Returns log(1 + number), computed in a way that is accurate even
when the value of number is close to zero
 log — Natural logarithm
 max — Find highest value
 min — Find lowest value
 mt_getrandmax — Show largest possible random value
 mt_rand — Generate a better random value
 mt_srand — Seed the better random number generator
 octdec — Octal to decimal
 pi — Get value of pi
 pow — Exponential expression
 rad2deg — Converts the radian number to the equivalent number in degrees
 rand — Generate a random integer
 round — Rounds a float
 sin — Sine
 sinh — Hyperbolic sine
 sqrt — Square root
 srand — Seed the random number generator
 tan — Tangent
 tanh — Hyperbolic tangent

_____________________________________________________________________________
102 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Let's see some functions in details:

abs

Description ¶

number abs ( mixed $number )


Returns the absolute value of number.

Parameters ¶

number

The numeric value to process

Return Values ¶

The absolute value of number. If the argument number is of type float, the return
type is also float, otherwise it isinteger (as float usually has a bigger value
range than integer).

Examples ¶

Example #1 abs() example

<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5); // 5 (integer)
echo abs(-5); // 5 (integer)
?>

acos — Arc cosine

_____________________________________________________________________________
103 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Description ¶

float acos ( float $arg )

Returns the arc cosine of arg in radians. acos() is the complementary function of
cos(), which means thata==cos(acos(a)) for every value of a that is within acos()'
range.

Parameters ¶

arg

The argument to process

Return Values ¶

The arc cosine of arg in radians.

acosh — Inverse hyperbolic cosine

Description ¶

float acosh ( float $arg )

Returns the inverse hyperbolic cosine of arg, i.e. the value whose
hyperbolic cosine is arg.

Parameters ¶

arg

The value to process

Return Values ¶

The inverse hyperbolic cosine of arg

_____________________________________________________________________________
104 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
exp — Calculates the exponent of e

Description ¶

float exp ( float $arg )

Returns e raised to the power of arg.

Note:
'e' is the base of the natural system of logarithms, or approximately
2.718282.
Parameters ¶

arg

The argument to process

Return Values ¶

'e' raised to the power of arg

Examples ¶

Example #1 exp() example

<?php

echo exp(12) . "\n";

echo exp(5.7);

?>

The above example will output:

1.6275E+005

298.87

_____________________________________________________________________________
105 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Working with string functions

They are sequences of characters, like "PHP supports string operations".

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

This will produce the following result:

There are no artificial limits on string length - within the bounds of available memory,
you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP:

Certain character sequences beginning with backslash (\) are replaced with special
characters

Variable names (starting with $) are replaced with string representations of their
values.
The escape-sequence replacements are:
 \n is replaced by the newline character

 \r is replaced by the carriage-return character


_____________________________________________________________________________
106 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

 \t is replaced by the tab character

 \$ is replaced by the dollar sign itself ($)

 \" is replaced by a single double-quote (")

 \\ is replaced by a single backslash (\)

String Concatenation Operator


To concatenate two string variables together, use the dot (.) operator:

This will produce the following result:

Hello World 1234

If you look at the code above, you see that we used the concatenation operator two
times. This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty
space, to separate the two variables.

Using the strlen() function


The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":

This will produce the following result:

12

The length of a string is often used in loops or other functions, when it is


important to know when the string ends. (i.e. in a loop, we would want to stop
the loop after the last character in the string).

_____________________________________________________________________________
107 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Using the strpos() function


The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first
match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:

This will produce the following result:

As you can see, the position of the string "world" in our string is position 6. The reason
that it is 6, and not 7, is that the first position in the string is 0, and not 1.

System Variable (GET POST cookies & Session Forums)

There are two ways the browser client can send information to the web server.
 The GET Method
 The POST Method

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

Spaces are removed and replaced with the + character and any other non-
alphanumeric characters are replaced with a hexadecimal values. After the
information is encoded it is sent to the server.

The GET Method


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

 The GET method produces a long string that appears in your server logs, in the
browser's Location: box.
 The GET method is restricted to send up to 1024 characters only.

_____________________________________________________________________________
108 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
 Never use GET method if you have password or other sensitive information to
be sent to the server.
 GET can't be used to send binary data, like images or word documents, to the
server.
 The data sent by GET method can be accessed using QUERY_STRING
environment variable.
 The PHP provides $_GET associative array to access all the sent information
using GET method.

Try out the following example by putting the source code in test.php script.

_____________________________________________________________________________
109 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
The POST Method
The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.

 The POST method can be used to send ASCII as well as binary data.

 The data sent by POST method goes through HTTP header so security depends
on HTTP protocol. By using Secure HTTP you can make sure that your
information is secure.

 The PHP provides $_POST associative array to access all the sent information
using POST method.

Try out the following example by putting the source code in test.php script.

_____________________________________________________________________________
110 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

The $_REQUEST variable


The PHP $_REQUEST variable contains the contents of both $_GET, $_POST,
and $_COOKIE. We will discuss $_COOKIE variable when we will explain about
cookies.

The PHP $_REQUEST variable can be used to get the result from form data
sent with both the GET and POST methods.
Try out following example by putting the source code in test.php script.

Here $_PHP_SELF variable contains the name of self script in which it is being
called.

COOKIES

Cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age,
or identification number etc.
_____________________________________________________________________________
111 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Browser stores this information on local machine for future use.

When next time browser sends any request to web server then it sends
those cookies.

The Anatomy of a Cookie


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

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path
and a domain. The name and value will be URL encoded. The expires field is an
instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and
domain of the cookie, it will resend the cookie to the server.The browser's headers
might look something like this:

A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above
cookie can be accessed using $HTTP_COOKIE_VARS["name"].

_____________________________________________________________________________
112 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Setting Cookies with PHP
PHP provided setcookie() function to set a cookie. This function requires up to six
arguments and should be called before <html> tag. For each cookie this function has
to be called separately.

Here is the detail of all the arguments:


Name - This sets the name of the cookie and is stored in an environment variable
called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value -This sets the value of the named variable and is the content that you
actually want to store.

Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan
1970. After this time cookie will become inaccessible. If this parameter is not set
then cookie will automatically expire when the Web Browser is closed.

Path - This specifies the directories for which the cookie is valid. A single forward
slash character permits the cookie to be valid for all directories.

Domain - This can be used to specify the domain name in very large domains
and must contain at least two periods to be valid. All cookies are only valid for
the host and domain which created them.

Security - This can be set to 1 to specify that the cookie should only be sent by
secure transmission using HTTPS otherwise set to 0 which mean cookie can be
sent by regular HTTP.

SESSIONS
An alternative way to make data accessible across the various pages of an
entire website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered


session variables and their values are stored. This data will be available to all
pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file
called session.save_path. Bore using any session variable make sure you have
setup this path.

When a session is started, the following actions take place:

PHP first creates a unique identifier for that particular session which is a
random string of 32 hexadecimal numbers such as
3c7foj34c3jj973hjkop2fc937e3443.
_____________________________________________________________________________
113 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

A cookie called PHPSESSID is automatically sent to the user's computer to


store unique session identification string.

A file is automatically created on the server in the designated temporary


directory and bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value from a session variable, PHP
automatically gets the unique session identifier string from the PHPSESSID
cookie and then looks in its temporary directory for the file bearing that name
and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the
server will terminate the session after a predetermined period of time,
commonly 30 minutes duration.

Starting a PHP Session


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

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

The following example starts a session and then registers a variable called counter
that is incremented each time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result:

_____________________________________________________________________________
114 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

_____________________________________________________________________________
115 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This function does not
need any argument and a single call can destroy all the session variables. If you want
to destroy a single session variable then you can use unset() function to unset a
session variable.
Here is the example to unset a single variable:

Here is the call which will destroy all the session variables:

Activity-1: (Answer the following questions)


1. Explain built in functions( print() include() header() phpinfo() )
2. What are the different mathematical operations in PHP?
3. Explain $_SERVER.

Activity-2:
Perform the below exercise till you are confident.
1. Write a function to calculate the factorial of a number (a non-negative integer). The
function accepts the number as an argument.
Solution: PHP Code
<?php
function factorial_of_a_number($n)
{
if($n ==0)
{
return 1;
}
else
{
return $n * factorial_of_a_number($n-1);
}
}
print_r(factorial_of_a_number(4)."\n");
?>

_____________________________________________________________________________
116 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
2. Write a function to check a number is prime or not.

Note: A prime number (or a prime) is a natural number greater than 1 that has no
positive divisors other than 1 and itself.

Solution: PHP Code

<?php
function IsPrime($n)
{
for($x=2; $x<$n; $x++)
{
if($n %$x ==0)
{
return 0;
}
}
return 1;
}
$a = IsPrime(3);
if ($a==0)
echo 'This is not a Prime Number.....'."\n";
else
echo 'This is a Prime Number..'."\n";
?>

3. Write a PHP function that checks if a string is all lower case.

Solution: PHP Code

<?php
function is_str_lowercase($str1)
{
for ($sc = 0; $sc < strlen($str1); $sc++) {
if (ord($str1[$sc]) >= ord('A') &&
ord($str1[$sc]) <= ord('Z')) {
return false;
}
}
return true;
}
var_dump(is_str_lowercase('abc def ghi'));
var_dump(is_str_lowercase('abc dEf ghi'));
?>
_____________________________________________________________________________
117 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
UNIT IV
Working with forms
http://www.webreference.com/programming/php/working_with_forms/index.html

Forms are how your users talk to your scripts. To get the most out of PHP, you must
master forms. The first thing you need to understand is that although PHP makes it
easy to access form data, you must be careful of how you work with the data.

Security Measures: Forms Are Not Trustworthy

A common mistake that novices make is to trust the data provided by an HTML form. If you
have a drop-down menu that only allows the user to enter one of three values, you must still
check those values. As mentioned in Chapter 3, you also cannot rely on JavaScript to stop
people from sending whatever they like to your server.

Your site's users can write their own form in HTML to use against your server; users can also
bypass the browser entirely and use automatic tools to interact with web scripts. You should
assume that people will mess around with parameters when you put a script on the Web,
because they might be trying to discover an easier way to use your site (though they could be
attempting something altogether less beneficial).

To ensure that your server is safe, you must verify all data that your scripts receive.

Verification Strategies

There are two approaches to checking form data: blacklisting and whitelisting.

Blacklisting is the process of trying to filter out all bad data by assuming that form
submissions are valid and then explicitly seeking out bad data. In general, this
technique is ineffective and inefficient. For example, let's say that you're trying to
eliminate all "bad" characters from a string, such as quotes. You might search for and
replace quotation marks, but the problem is that there will always be bad characters
you didn't think of. In general, blacklisting assumes that most of the data you receive
is friendly.
A better assumption to make about form data you're receiving is that it's inherently
malicious; thus, you should filter your data in order to accept only valid data
submissions. This technique is called whitelisting. For example, if a string should
consist of only alphanumeric characters, then you can check it against a regular
expression that matches only an entire string of A-Za-z0-9. Whitelisting may also
include forcing data to a known range of values or changing the type of a value. Here
is an overview of a few specific tactics:

_____________________________________________________________________________
118 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
 If the value should be a number, use the is_numeric()
function to verify the value. You can force a value to an
integer using the intval() function.
 If the value should be an array, use is_array().
 If the value should be a string, use is_string(). To force it,
use strval().
 If the value should be null, use is_null().
 If the value should be defined, use isset().

Fetching Form Variables Consistently and Safely

You should pull form data from predefined server variables. All data passed on to your
web page via a posted form is automatically stored in a large array called $_POST, and
all GET data is stored in a large array called$_GET. File upload information is stored
in a special array called $_FILES (see "#54: Uploading Images to a Directory" on page
97 for more information on files). In addition, there is a combined variable called
$_REQUEST.

To access the username field from a POST method form, use $_POST['username']. Use
$_GET['username']if the username is in the URL. If you don't care where the value
came from, use $_REQUEST['username'].

_____________________________________________________________________________
119 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

$_REQUEST is a union of the $_GET, $_POST, and $_COOKIE arrays. If you have two
or more values of the same parameter name, be careful of which one PHP uses. The
default order is cookie, POST, then GET.

There has been some debate on how safe $_REQUEST is, but there shouldn't be.
Because all of its sources come from the outside world (the user's browser), you need
to verify everything in this array that you plan to use, just as you would with the other
predefined arrays. The only problems you might have are confusing bugs that might
pop up as a result of cookies being included.

Trimming Excess Whitespace

Excess whitespace is a constant problem when working with form data. The trim()
function is usually the first tool a programmer turns to, because it removes any excess
spaces from the beginning or end of a string. For example, "Wicked Cool PHP "
becomes "Wicked Cool PHP." In fact, it's so handy that you may find yourself using it
on almost every available piece of user-inputted, non-array data:

$user_input = trim($user_input);
But sometimes you have excessive whitespace inside a string—when someone may be
cutting and copying information from an email, for instance. In that case, you can
replace multiple spaces and other whitespace with a single space by using the
preg_replace() function. The reg stands for regular expression, a powerful form of
pattern matching.

_____________________________________________________________________________
120 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Importing Form Variables into an Array

One of the handiest tricks you can use in PHP is not actually a PHP trick but an HTML
trick. When a user fills out a form, you'll frequently check the values of several
checkboxes. For example, let's say you're taking a survey to see what sorts of movies
your site's visitors like, and you'd like to automatically insert those values into a
database called customer_preferences. The hard way to do that is to give each checkbox
a separate name on the HTML form, as shown here:

Unfortunately, when you process the form on the next page, you'll need a series of
if/then loops to check the data—one loop to check the value of $action, one to check
the value of $drama, and so forth. Adding a new checkbox to the HTML form results in
yet another if/then loop to the processing page.
A great way to simplify this procedure is to store all of the checkbox values in a single
array by adding [] after the name, like this:

When PHP gets the data from a form like this, it stores the checked values in a single
array. You can loop through the array this way:

_____________________________________________________________________________
121 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Figure: A form with an array of checkboxes

Not only does this technique work for checkboxes, but it's extremely handy for
processing arbitrary numbers of rows. For example, let's say we have a shopping
menu where we want to show all the items in a given category. Although we may not
know how many items will be in a category, the customer should be able to enter a
quantity into a text box for all items he wants to buy and add all of the items with a
single click.

Form elements (Text Area Password Radio Button The Combo Box
Hidden Field and image)
PHP script for SELECT OPTION FIELD:

HTML select tag allows user to choose one or more options from the given drop down
list. Below example contains PHP script to get a single or multiple selected values from
given HTML select tag. We are covering following operations on select option field
using PHP script.

To get value of a selected option from select tag:

<form action="#" method="post">

<select name="Color">

<option value="Red">Red</option>

<option value="Green">Green</option>

<option value="Blue">Blue</option>

<option value="Pink">Pink</option>

<option value="Yellow">Yellow</option>

_____________________________________________________________________________
122 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

</select>

<input type="submit" name="submit" value="Get Selected Values" />

</form>

<?php

if(isset($_POST['submit'])){

$selected_val = $_POST['Color']; // Storing Selected Value In Variable

echo "You have selected :" .$selected_val; // Displaying Selected Value

?>

To get value of multiple select option from select tag, name attribute in HTML <select>
tag should be initialize with an array [ ]:

<form action="#" method="post">

<select name="Color[]" multiple> // Initializing Name With An Array

<option value="Red">Red</option>

<option value="Green">Green</option>

<option value="Blue">Blue</option>

<option value="Pink">Pink</option>

<option value="Yellow">Yellow</option>

</select>

<input type="submit" name="submit" value="Get Selected Values" />

</form>

<?php

if(isset($_POST['submit'])){

// As output of $_POST['Color'] is an array we have to use foreach Loop to display


individual value

foreach ($_POST['Color'] as $select)

{
_____________________________________________________________________________
123 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

echo "You have selected :" .$select; // Displaying Selected Value

?>

PHP script for RADIO BUTTON FIELD:

HTML <input type=”radio”> allows user to choose one option from the given choices.
Below codes contains PHP script to get a selected value from given HTML <input
type=”radio”>. To get selected value of a radio button:

<form action="" method="post">

<input type="radio" name="radio" value="Radio 1">Radio 1

<input type="radio" name="radio" value="Radio 2">Radio 2

<input type="radio" name="radio" value="Radio 3">Radio 3

<input type="submit" name="submit" value="Get Selected Values" />

</form>

<?php

if (isset($_POST['submit'])) {

if(isset($_POST['radio']))

echo "You have selected :".$_POST['radio']; // Displaying Selected Value

?>

In below example, we have created a form having select tag and some radio buttons,
As user submits it, Value of selected options will be displayed.

_____________________________________________________________________________
124 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Hidden Fields
http://www.informit.com/articles/article.aspx?p=29587&seqNum=7

Using Hidden Fields to Save State

The script in Listing 9.9 has no way of knowing how many guesses a user has made.
We can use a hidden field to keep track of this. A hidden field behaves exactly the
same as a text field, except that the user cannot see it, unless he views the HTML
source of the document that contains it. Listing 9.10 adds a hidden field to the
number guessing script and some PHP to work with it.

_____________________________________________________________________________
125 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

The hidden field on line 28 is given the name "num_tries". We also use PHP to write its
value. While we're at it, we do the same for the "guess" field on line 27, so that the
user can always see his last guess. This technique is useful for scripts that parse user
input. If we were to reject a form submission for some reason we can at least allow our
user to edit his previous query.

TIP

When you need to output the value of an expression to the browser, you can of course
use print()or echo(). When you are entering PHP mode explicitly to output such a value
you can also take advantage of a special extension to PHP's short opening tags. If you
add an equals (=) sign to the short PHP opening tag, the value contained will be
printed to the browser.

<? print $test;?>

is equivalent to

<?=$test?>

_____________________________________________________________________________
126 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Within the main PHP code, we use a ternary operator to increment the $num_tries
variable. If the $num_tries variable is set, we add one to it and reassign this
incremented value; otherwise, we initialize $num_tries to 0. Within the body of the
HTML, we can now report to the user how many guesses he has made.

CAUTION

Don't entirely trust hidden fields. You don't know where their values have been! This
isn't to say that you shouldn't use them, just be aware that your users are capable of
viewing and amending source code should they want to cheat your scripts.

Image
Images appear in the form of logos, buttons, photographs, charts, advertisements, and
icons. Many of these images are static, built with tools such as Photoshop and never
changed. But many are dynamically created— from advertisements for Amazon’s
referral program that include your name to Yahoo! Finance’s graphs of stock performance.

Embedding an Image in a Page


A common misconception is that there is a mixture of text and graphics flowing across
a single HTTP request. After all, when you view a page you see a single page containing
such a mixture. It is important to understand that a standard web page containing
text and graphics is created through a series of HTTP requests from the web browser,
each answered by a response from the web server. Each response can contain one and
only one type of data, and each image requires a separate HTTP request and web
server response. Thus, if you see a page that contains some text and two images, you
know that it has taken three HTTP requests and corresponding responses to construct
this page.

Take this HTML page, for example:

The series of requests sent by the web browser for this page looks something like this:
GET /page.html HTTP/1.0
GET /image1.jpg HTTP/1.0
GET /image2.jpg HTTP/1.0

_____________________________________________________________________________
127 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

The web server sends back a response to each of these requests. The Content-Type
headers in these responses look like this:

Content-Type: text/html
Content-Type: image/jpeg
Content-Type: image/jpeg

To embed a PHP-generated image in an HTML page, pretend that the PHP script that
generates the image is actually the image. Thus, if we have image1.php and
image2.php scripts that create images, we can modify the previous HTML to look like
this:

<html>
<head>
<title>Example Page</title>
</head>
<body>
This page contains two images.
<img src="image1.php" alt="Image 1">
<img src="image2.php" alt="Image 2">
</body>
</html>

Instead of referring to real images on your web server, the image tags nowrefer to the
PHP scripts that generate the images. Furthermore, you can pass variables to these
scripts, so instead of having separate
scripts to generate the two images, you could write your image tags like this:

<img src="image.php?num=1" alt="Image 1">


<img src="image.php?num=2" alt="Image 2">

Then, inside image.php, you can access $_GET['num'] (or $num, if register_globals is
on) to generate the appropriate image.

Uploading files to the Web Server using PHP


A PHP script can be used with a HTML form to allow users to upload files to the
server. Initially files are uploaded into a temporary directory and then relocated to a
target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used
for file uploads as upload_tmp_dir and the maximum permitted size of files that can
be uploaded is stated as upload_max_filesize. These parameters are set into PHP
configuration filephp.ini
The process of uploading a file follows these steps:
 The user opens the page containing a HTML form featuring a text files, a browse
button and a submit button.

 The user clicks the browse button and selects a file to upload from the local PC.

_____________________________________________________________________________
128 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
 The full path to the selected file appears in the text filed then the user clicks the
submit button.

 The selected file is sent to the temporary directory on the server.

 The PHP script that was specified as the form handler in the form's action
attribute checks that the file has arrived and then copies the file into an
intended directory.

 The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to
have permissions set that enable file writing. If either is set to be read-only then
process will fail.
An uploaded file could be a text file or image file or any document.

Creating an upload form


The following HTML code below creates an uploader form. This form is having method attribute
set to post and enctype attribute is set to multipart/form-data

_____________________________________________________________________________
129 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
This will display the following result:

Creating an upload script


There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value assigned
to the input's name attribute in uploading form was file, then PHP would create following five
variables:
$_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web server.

$_FILES['file']['name'] - the actual name of the uploaded file.

$_FILES['file']['size'] - the size in bytes of the uploaded file.

$_FILES['file']['type'] - the MIME type of the uploaded file.

$_FILES['file']['error'] - the error code associated with this file upload.

The following example below attempts to copy a file uploaded by the HTML Form listed in
previous section page to /var/www/html directory which is document root of your PHP
server and it will display all the file's detail upon completion. Please note that if you are going
to display uploaded file then don't try with binary files like images or word document.

_____________________________________________________________________________
130 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Here is the code of uploader.php script which will take care of uploading a file.

When you will upload a file using upload form and upload script, it will display
following result:

_____________________________________________________________________________
131 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Building a challenge and response subsystem and understanding the


functionality of the FORM attribute Method
http://www.homeandlearn.co.uk/php/php4p1.html

If you know a little HTML, then you know that the FORM tags can be used to interact
with your users. Things that can be added to a form are the likes of text boxes, radio
buttons, check boxes, drop down lists, text areas, and submit buttons. A basic HTML
form with a textbox and a Submit button looks like this:

<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>

<FORM NAME ="form1" METHOD =" " ACTION = "">

<INPUT TYPE = "TEXT" VALUE ="username">


<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">

</FORM>

</body>
</html>

We won't explain what all the HTML elements do, as this is a book on PHP.
Some familiarity with the above is assumed. But we'll discuss the METHOD,
ACTION and SUBMIT attributes in the form above, because they are
important.

The above form can be found in the files you download. It's in the scripts
folder, and is calledbasicForm.php. Use it as a template, if you like.

So, create the form above. Save your work as basicForm.php. (This name will
be VERY important!) Start your server, and make sure the form loads ok in
your browser. You should be able to see a text box and a Submit button. Here's
what it should look like:

_____________________________________________________________________________
132 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

If a user comes to your site and has to login, for example, then you'll need to
get the details from textboxes. Once you get the text that the user entered, you
then test it against a list of your users (this list is usually stored on a database,
which we'll see how to code for in a later section). First, you need to know
about the HTML attributes METHOD, ACTION and SUBMIT. We'll explore these
in the next few sections.

If you look at the first line of our form from the previous page, you'll notice a
METHOD attribute:

<FORM NAME ="form1" METHOD =" " ACTION = "">

The Method attribute is used to tell the browser how the form information
should be sent. The two most popular methods you can use are GET and
POST. But our METHOD is blank. So change it to this:

<FORM NAME ="form1" METHOD ="GET" ACTION = "">

To see what effect using GET has, save your work again and then click the
Submit button on your form. You should see this:

_____________________________________________________________________________
133 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
The thing to notice here is the address bar. After basicForm.php, we have the
following:

?Submit1=Login

This is a consequence of using the GET method. The data from the form ends
up in the address bar. You'll see a question mark, followed by form data. In the
image above, Submit1 was the NAME of the button, and Login was the VALUE
of the button (the text on the button). This is what is being returned by the
GET method. You use the GET method when the data you want returned is not
crucial information that needs protecting.

Regular Expressions: Engine, Types of Regular Expressions, symbols


used in Regular Expressions
Regular expressions are nothing more than a sequence or pattern of characters itself.
They provide the foundation for pattern-matching functionality.
Using regular expression, you can search a particular string inside another string, you
can replace one string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression. You can use any of them based
on your comfort.
 POSIX Regular Expressions

 PERL Style Regular Expressions

POSIX Regular Expressions


The structure of a POSIX regular expression is not dissimilar to that of a typical
arithmetic expression: various elements (operators) are combined to form more
complex expressions.

The simplest regular expression is one that matches a single character, such as g,
inside strings such as g, haggle, or bag.

Let’s give explanation for few concepts being used in POSIX regular expression. After
that we will introduce you with regular expression related functions.

_____________________________________________________________________________
134 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions.
They are used to find a range of characters.

The ranges shown above are general; you could also use the range [0-3] to
match any decimal digit ranging from 0 through 3, or the range [b-v] to match
any lowercase character ranging from b through v.

Quantifiers:
The frequency or position of bracketed character sequences and single
characters can be denoted by a special character. Each special character
having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a
character sequence.

_____________________________________________________________________________
135 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Examples
Following examples will clear your concepts about matching characters.

_____________________________________________________________________________
136 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Predefined Character Ranges
For your programming convenience several predefined character ranges, also known
as character classes, are available. Character classes specify an entire range of
characters, for example, the alphabet or an integer set:

PHP's Regexp POSIX Functions


PHP currently offers seven functions for searching strings using POSIX-style regular
expressions:

_____________________________________________________________________________
137 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

PERL Style Regular Expressions


Perl-style regular expressions are similar to their POSIX counterparts. The POSIX
syntax can be used almost interchangeably with the Perl-style regular expression
functions. In fact, you can use any of the quantifiers introduced in the previous POSIX
section.

Let’s give explanation for few concepts being used in PERL regular expressions. After
that, we will introduce you with regular expression related functions.

Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts
to give the combination a special meaning.

For instance, you can search for large money sums using the '\d'
metacharacter:/([\d]+)000/, Here \d will search for any string of numerical character.
Following is the list of metacharacters which can be used in PERL Style Regular
Expressions.

_____________________________________________________________________________
138 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Modifiers
Several modifiers are available that can make your work with regexps much easier,
like case sensitivity, searching in multiple lines etc.

PHP's Regexp PERL Compatible Functions


PHP offers following functions for searching strings using Perl-compatible regular
expressions:

_____________________________________________________________________________
139 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

Error handling in PHP, Displaying errors, warnings

Error handling is the process of catching errors raised by your program and
then taking appropriate action. If you would handle errors properly then it may
lead to many unforeseen consequences. It is very simple in PHP to handle
errors.

Using die() function


While writing your PHP program you should check all possible error condition
before going ahead and take appropriate action when required.
Try the following example without having /tmp/test.xt file and with this file.

You can thus write an efficient code. Using the above technique, you can stop your
program whenever it errors out and display more meaningful and user-friendly
message.

Defining Custom Error Handling Function


You can write your own function to handling any error. PHP provides you a framework
to define error-handling function.
This function must be able to handle a minimum of two parameters (error level and
error message) but can accept up to five parameters (optionally: file, line-number, and
the error context):

_____________________________________________________________________________
140 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Syntax

Possible Error levels


These error report levels are the different types of error the user-defined error handler
can be used for. These values cab used in combination using | operator

_____________________________________________________________________________
141 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

All the above error level can be set using following PHP built-in library function where
level cab be any of the value defined in above table.

Following is the way you can create one error handling function:

_____________________________________________________________________________
142 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Once you define your custom error handler you need to set it using PHP built-in
library set_error_handler function. Now let’s examine our example by calling a
function which does not exist.

types of errors, error levels in PHP (covered above)

logging Errors and Ignoring errors.

http://php.net/manual/en/book.errorfunc.php

Error Handling Functions

 debug_backtrace — Generates a backtrace

 debug_print_backtrace — Prints a backtrace

 error_clear_last — Clear the most recent error


 error_get_last — Get the last occurred error

_____________________________________________________________________________
143 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
 error_log — Send an error message to the defined error handling routines


 error_reporting — Sets which PHP errors are reported

The error_reporting() function sets the error_reporting directive at runtime. PHP has
many levels of errors, using this function sets that level for the duration (runtime) of
your script. If the optional level is not set,error_reporting() will just return the current
error reporting level.

 restore_error_handler — Restores the previous error handler function

Used after changing the error handler function using set_error_handler(), to revert to
the previous error handler (which could be the built-in or a user defined function).

 restore_exception_handler — Restores the previously defined exception handler


function

 set_error_handler — Sets a user-defined error handler function

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during
runtime, for example in applications in which you need to do cleanup of
data/files when a critical error happens, or when you need to trigger an error
under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely


bypassed for the error types specified by error_types unless the callback
function returns FALSE. error_reporting() settings will have no effect and your
error handler will be called regardless - however you are still able to read the
current value of error_reporting and act appropriately. Of particular note is that
this value will be 0 if the statement that caused the error was prepended by the
@ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler


function returns, script execution will continue with the next statement after
the one that caused an error.
_____________________________________________________________________________
144 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

The following error types cannot be handled with a user defined function:
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in
the file where set_error_handler() is called.

If errors occur before the script is executed (e.g. on file uploads) the custom
error handler cannot be called since it is not registered at that time.

 set_exception_handler — Sets a user-defined exception handler function

Sets the default exception handler if an exception is not caught within a


try/catch block. Execution will stop after the exception_handler is called.
 trigger_error — Generates a user-level error/warning/notice message

Used to trigger a user error condition, it can be used in conjunction with the
built-in error handler, or with a user defined function that has been set as the
new error handler (set_error_handler()).
This function is useful when you need to generate a particular response to an
exception at runtime.
 user_error — Alias of trigger_error

This function is an alias of: trigger_error().

These are functions dealing with error handling and logging. They allow you to
define your own error handling rules, as well as modify the way the errors can
be logged. This allows you to change and enhance error reporting to suit your
needs.

Using these logging functions, you can send messages directly to other
machines, to an email, to system logs, etc., so you can selectively log and
monitor the most important parts of your applications and websites.

_____________________________________________________________________________
145 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Installation
The error and logging functions are part of the PHP core. There is no installation
needed to use these functions.

Runtime Configuration
The behavior of these functions is affected by settings in php.ini. These settings are
defined below.

_____________________________________________________________________________
146 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

PHP Error and Logging Constants


PHP: indicates the earliest version of PHP that supports the constant. You can use any
of the constant while configuring your php.ini file.

Activity-1: (Answer the following questions)


1. How to trim Excess Whitespace.

2. Explain Regular Expressions.

3. Error handling in PHP.

Activity-2
Perform the below exercise till you are confident.
1. Write a PHP script that checks if a string contains another string.

Solution PHP Code:

<?php
$pattern = '/[^\w]fox\s/';
if (preg_match($pattern, 'The quick brown fox jumps over the lazy dog'))
{
echo "'fox' is present..."."\n";
}
else
echo "'fox' is not present..."."\n";
?>

_____________________________________________________________________________
147 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
2. Write a PHP script that removes the whitespaces from a string.

Sample string: 'The quick " " brown fox'

Solution PHP Code:

<?php
$str1 = 'The quick " " brown fox';
echo preg_replace('/\s+/', '', $str1)."\n";
?>

3. Write a PHP script to remove nonnumeric characters except comma and dot.

Sample string : '$123,34.00A'

Solution PHP Code:


<?php
$str1 = "$12,334.00A";
echo preg_replace("/[^0-9,.]/", "", $str1)."\n";
?>

4. Write a PHP script to remove new lines (characters) from a string.

Sample strings: "Twinkle, twinkle, little star,\nHow I wonder what you


are.\nUp above the world so high,\nLike a diamond in the sky.";

Solution PHP Code:


<?php
$str = "Twinkle, twinkle, little star,\nHow I wonder what you are.\nUp above
the world so high,\nLike a diamond in the sky.";
echo preg_replace('/\s+/', ' ', trim($str))."\n";
?>

_____________________________________________________________________________
148 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
UNIT V
Data base connectivity using PHP (MySQL ODBC ORACLE SQL),
Performing executing Commands

PHP will work with virtually all database software, including Oracle and Sybase but
most commonly used is freely available MySQL database .

What you should already have?


 You have gone through MySQL tutorial to understand MySQL Basics.

 Downloaded and installed a latest version of MySQL.

 Created database user guest with password guest123.

 If you have not created a database then you would need root user and its
password to create a database.

We have divided this chapter in the following sections:

 Connecting to MySQL database - Learn how to use PHP to open and close a
MySQL database connection.

 Create MySQL Database Using PHP - This part explains how to create MySQL
database and tables using PHP.

 Delete MySQL Database Using PHP - This part explains how to delete MySQL
database and tables using PHP.

 Insert Data To MySQL Database - Once you have created your database and
tables, then you would like to insert your data into created tables. This session
will take you through real example on data insert.

 Retrieving Data From MySQL Database - Learn how to fetch records from
MySQL database using PHP.

 Using Paging through PHP - This one explains how to show your query result
into multiple pages and how to create the navigation link.

 Updating Data Into MySQL Database - This part explains how to update
existing records into MySQL database using PHP.

 Deleting Data From MySQL Database - This part explains how to delete or
purge existing records from MySQL database using PHP.

 Using PHP To Backup MySQL Database - Learn different ways to take backup
of your MySQL database for safety purpose.
_____________________________________________________________________________
149 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
https://www.siteground.com/tutorials/php-mysql/database_connection.htm

You should establish a connection to the MySQL database.

This is an extremely important step because if your script cannot connect to its
database, your queries to the database will fail.

A good practice when using databases is to set the username, the password and
the database name values at the beginning of the script code. If you need to
change them later, it will be an easy task.

$username="your_username";$password="your_password";$database="your_database"
;

You should replace "your_username", "your_password" and "your_database" with


the MySQL username, password and database that will be used by your script.

At this point you may be wondering if it is a security risk to keep your password in
the file. You don't need to worry because the PHP source code is processed by the
server before being sent to the browser. So the visitor will not see the script's code
in the page source.

Next you should connect your PHP script to the database. This can be done with
the mysql_connect PHP function:

mysql_connect(localhost,$username,$password);

This line tells PHP to connect to the MySQL database server at 'localhost'
(localhost is the MySQL server which usually runs on the same physical server as
your script).

After the connection is established you should select the database you wish to use.
This should be a database to which your username has access to. This can be
completed through the following command:

@mysql_select_db($database) or die( "Unable to select database");

_____________________________________________________________________________
150 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
It tells PHP to select the database stored in the variable $database (in our case it
will select the database "your_database"). If the script cannot connect it will stop
executing and will show the error message:

Unable to select database

The 'or die' part is useful as it provides debugging functionality. However, it is not
essential.

Another important PHP function is:

mysql_close();

This is a very important function as it closes the connection to the database


server. Your script will still run if you do not include this function. And too many
open MySQL connections can cause problems for your account. This it is a good
practice to close the MySQL connection once all the queries are executed.

You have connected to the server and selected the database you want to work
with. You can start querying the database now.

There are at least two ways to query a database. One is to enter the command in
PHP.

Another way is to define the command as a variable.

In this part of the tutorial we will show the first way. The command will look like
this:

mysql_query($query);

The command can be repeated over and over again in the source code. All you
need to do is to change the variable.

Here is the complete code that should be used to create a MySQL table in PHP:

<?php$user="username";$password="password";$database="database";
my s ql_ c on n ec t (l o c al h ost , $ u s er , $ p a s sw or d ); @ m ys ql _ s el e ct _ d b ( $ d at a b as e ) or di e(

_____________________________________________________________________________
151 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
"Unable to select database");$query="CREATE TABLE tablename(id int(6)
NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15)
NOT NULL,field1-name varchar(20) NOT NULL,field2-name varchar(20)
NOT NULL,field3-name varchar(20) NOT NULL,field4-name varchar(30) NOT NULL,
f ie l d 5 -n a m e v ar ch ar ( 3 0) N O T NU LL, P RI M A RY K E Y (i d) , U NI QU E id ( i d), KE Y i d_ 2
(id))";mysql_query($query);mysql_close();?>

Enter your database, MySQL username and MySQL password in the appropriate
positions on the first three lines above.

The next query should fill in the table. Here is a sample one:

$query = "INSERT INTO tablename VALUES ('','$field1-name','$field2-name'


,'$field3-name','$field4-name','$field5-name')";

You can't insert more values than the number of fields you have created with the
first query.

How to Display MySQL Table Data


After you have created the table and entered the data, you will probably need to
display it. This is usually done using basic HTML code which invokes a PHP script.

We will start the example from the beginning. We will populate a new database
table with data.

The following HTML code will collect the data from the text boxes and pass it to the
PHP script:

<form action="insert.php" method="post">


Value1: <input type="text" name="field1-name" />
Value2: <input type="text" name="field2-name" />
Value3: <input type="text" name="field3-name" />
Value4: <input type="text" name="field4-name" />
Value5: <input type="text" name="field5-name" />
<input type="Submit" /></form>

The next thing you need is a new PHP script which will enter the data in the
database.

_____________________________________________________________________________
152 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

< ? p h p $ u s e r n a m e = " u s e r n a m e " ;


$ p a s s w o r d = " p a s s w o r d " ; $ d a t a b a s e = " y o u r _ d a t a b a s e " ;
$ f i e l d 1 - n a m e = $ _ P O S T [ ' V a l u e 1 ' ] ;
$ f i e l d 2 - n a m e = $ _ P O S T [ ' V a l u e 2 ' ] ;
$ f i e l d 3 - n a m e = $ _ P O S T [ ' V a l u e 3 ' ] ;
$ f i e l d 4 - n a m e = $ _ P O S T [ ' V a l u e 4 ' ] ;
$ f i e l d 5 - n a m e = $ _ P O S T [ ' V a l u e 5 ' ] ;
m y s q l _ c o n n e c t ( l o c a l h o s t , $ u s e r n a m e , $ p a s s w o r d ) ;
@mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO tablename VALUES('','$field1-name','$field2-name',
'$field3-name','$field4-name','$field5-name')";mysql_query($query);mysql_close();?>

This script should be saved as insert.php so that it can be called by the HTML
form.

Now that you have at least one record in your database, you may want to know
how you can output this data using PHP.

The first command you will need to use is the SELECT FROM MySQL statement:

SELECT * FROM tablename

This is a basic MySQL query which will tell the script to select all the records from
the tablename table. After the query execution the result will be assigned to a
variable:

$query="SELECT * FROM tablename";$result=mysql_query($query);

The whole content of the table is now included in a PHP array with the name
$result. Before you can output this data you should change each piece into a
separate variable. There are two stages.

The first one is counting the rows. Before you can go through the data in your
result variable, you should know the number of the database rows. You could, of
course, just type this into your code but it is not a very good solution as the script
code will have to be changed every time a new row is added. Instead you can use
the command:

_____________________________________________________________________________
153 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

$num=mysql_numrows($result);

The $num value will be the number of rows stored in $result. This will be used in
a loop to get all the data and display it on the screen.

The second stage is to set up the loop. It will take each row of the result and print
the data stored there. In the code below, $i is the number of times the loop runs.
In this way all the records are displayed.

$i=0;while ($i < $num) {CODE$i++;}

This is a basic PHP loop and will execute the code the correct number of times.
Each time $i will be incremented by one. This is useful, as $i will tell the script
which line of the results should be read. As the first line in MySQL output is 0,
this will work correctly.

The final part of the output script is to assign each piece of data to its own
variable:

$variable=mysql_result($result,$i,"fieldname");

So to take each individual piece of data in our database we would use the
following:

$field1-name=mysql_result($result,$i,"field1-name");
$field2-name=mysql_result($result,$i,"field2-name");
$field3-name=mysql_result($result,$i,"field3-name");
$field4-name=mysql_result($result,$i,"field4-name");
$field5-name=mysql_result($result,$i,"field5-name");

You do not need to get the ID field because there is no use for it in the output
page.

You can now write a full script to output the data. In this script the data is not
formatted when it is printed:

_____________________________________________________________________________
154 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

<?php$username="username";$password="password";
$database="your_database";mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM tablename";$result=mysql_query($query);
$num=mysql_numrows($result);mysql_close();
echo "<b>
<center>Database Output</center>
</b>
<br>
<br>";
$i=0;while ($i < $num) {$field1-name=mysql_result($result,$i,"field1-name");
$field2-name=mysql_result($result,$i,"field2-name");
$field3-name=mysql_result($result,$i,"field3-name");
$field4-name=mysql_result($result,$i,"field4-name");
$field5-name=mysql_result($result,$i,"field5-name");
echo "<b>
$field1-name $field2-name2</b>
<br>
$field3-name<br>
$field4-name<br>
$field5-name<hr>
<br>";$i++;}?>

This outputs a list of all the values stored in the database. This will give you a very
basic output. It is not useful for a working website. Instead, it would be better if
you could format it into a table and display the information in it. Doing the
formatting is not complicated. All you need to do is use HTML to print the result
by including the variables in the correct spaces. The easiest way to do this is by
closing your PHP tag and entering HTML normally. When you reach a variable
position, include it as follows:

<? echo $variablename; ?>

in the correct position in your code.

You can also use the PHP loop to repeat the appropriate code and include it as
part of a larger table. The final output is:

_____________________________________________________________________________
155 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

<html>
<body>
<?php$username="username";$password="password";$database="your_database";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM tablename";$result=mysql_query($query);
$num=mysql_numrows($result);mysql_close();?>
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td>
<font face="Arial, Helvetica, sans-serif">Value1</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value2</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value3</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value4</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value5</font>
</td>
</tr>
<?php$i=0;while ($i < $num) {$f1=mysql_result($result,$i,"field1");
$f2=mysql_result($result,$i,"field2");$f3=mysql_result($result,$i,"field3");
$f4=mysql_result($result,$i,"field4");$f5=mysql_result($result,$i,"field5");?>
<tr>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f4; ?></font>

_____________________________________________________________________________
156 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f5; ?></font>
</td>
</tr>
<?php$i++;}?>
</body>
</html>

PHP Mysql functions List:

Function Description
mysql_select_db($dbs[, $connect]) Select database for use
mysql_close($connect) Close the connection
mysql_query($query[, $connect]) Query the database, get results
mysql_num_rows($q_result) Get row number of a query result
mysql_connect($host,$user,$passwd) Opens a connect to server
mysql_drop_db($dbs,$connect) Delete database
mysql_create_db($dbs,$connect) Create database
Number of rows affected after an
mysql_affected_rows($connect)
operation
mysql_num_fields($q_result) Get field number of a query result
mysql_change_user($user,
Change MySQL user
$passwd[,$dbs,$connect])
mysql_data_seek($q_result, $row_number) Fetching data from the specified row
mysql_errno($connect) Get error ID
mysql_error($connect) Get error message
Get query result as associative array.
mysql_fetch_array($q_result[,$type]) $type includes MYSQL_ASSOC,
MYSQL_NUM, MYSQL_BOTH (default)
mysql_fetch_lengths($q_result) get each field length of a result set
mysql_fetch_object($q_result[,$type]) Get query result as an object
Get query result as an enumerated
mysql_field_row($q_result)
array
mysql_field_name($q_result,$field_index) Get name of enumerated field
mysql_fetch_field($q_result,[,$field_offset]) Get a field as an object
mysql_field_seek($q_result,$field_offset) Set result pointer to the field offset
mysql_field_table($q_result,$field_offset Get table name of the field

_____________________________________________________________________________
157 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
mysql_field_type($q_result,$field_offset) Get types of the field
Get flags of the enumerated field, e.g.
mysql_field_flags($q_result,$field_offset)
NULL, AUTO_INCREMENT
mysql_field_len($q_result,$field_offset) Get length of the enumerated field
Release the memory used by result
mysql_free_result($q_result)
set
get AUTO_INCREMENTED ID of
mysql_insert_id($connect)
INSERT operation
mysql_list_fields($dbs,$table[,$connect]) Get result ID in mysql_field functions
Get result pointer of databases on
mysql_list_dbs($connect)
mysqld
Get result pointer of tables in
mysql_list_tables($dbs[, $connect])
database
Create a permanent connect to the
mysql_pconnect($host,$user,$passwd) server database. mysql_close() can't
close it
mysql_result($q_result, $row_id, $field) Get single filed result.

Different types of Data Base Operations like Insertion deletion


update and query on data
http://www.phpforkids.com/php/php-mysql-database-running-queries.php

Running MYSQL Queries In PHP

The mysql_query() function is a "catch all" that can run about any MYSQL query that
you give it. Let's look into the execution of some standard insert, select, update and
delete statements.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password",
"database_name");
if (!$con) { die('Could Not Connect: ' . mysql_error($con) . mysql_errno($con)); }

$insert = mysqli_query($con, "INSERT INTO table_name (col1, col2) VALUES('Value


1', 'Value 2' );");
if (!$insert) { die (mysql_error($con)); }

$select = mysqli_query($con, "SELECT * FROM table_name;");


if (!$select) { die (mysql_error($con)); }

$update = mysqli_query($con, "UPDATE table_name SET col2 = 'Value' WHERE col2

_____________________________________________________________________________
158 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
LIKE 'Value 2';");
if (!$update) { die (mysql_error($con)); }

$delete = mysqli_query($con, "DELETE FROM table_name WHERE col2 LIKE


'Value';");
if (!$delete) { die (mysql_error($con)); }

mysqli_close($con);
?>

Handling MYSQL Query Results In PHP

Now, how do we handle the results of the MYSQL statements executed? Decisions, decisions...
That all depends on what you want to do.

The mysqli_num_rows() function, when handed the result of an executed SELECT or SHOW
statement, will return the number of rows that will be returned.

The mysqli_affected_rows() function, when handed the result of a recently executed statement,
will return how many rows were affected by the execution of the statement.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password",
"database_name");
$select = mysqli_query($con, "SELECT * FROM table_name;");
echo mysqli_num_rows($select) . ' rows were selected.';

$update = mysqli_query($con, "UPDATE table_name SET col2 = 'Value' WHERE col2


LIKE 'Value 2';");
echo mysqli_affected_rows($update) . ' rows were updated.';

mysqli_close($con);
?>

But perhaps the most useful functions are those that can help you identify and read
selected data. The two most common functions for this purpose are
mysqli_fetch_array() and mysqli_fetch_assoc().

_____________________________________________________________________________
159 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Using a while loop in combination with either of these two functions, we can come up
with a simple solution to process multiple results to an executed query.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password",
"database_name");
$result = mysql_query($con, "SELECT * FROM table_name;");

while ($list = mysqli_fetch_assoc($result)) {


echo 'Label 1: ' . $list['column_name_1'] . '<br>';
echo 'Label 2: ' . $list['column_name_2'] . '<br><br>';
}

mysqli_close($con);
?>

We can read it like this: While there is another row of results being returned from the executed
query, assign it to the $list array. Then, since we used the mysqli_fetch_assoc() function, the
array will be 'associated' with the name of each column of the database. We use those database
column names to identify the data that we want to display/format/use.

Substituting the mysqli_fetch_array() function is different only in the sense that you do not
need to memorize the column/field names in your database... You only need to memorize what
order they are in, so that they can be identified by number (beginning with '0').

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password",
"database_name");
$result = mysql_query($con, "SELECT * FROM table_name;");

while ($list = mysqli_fetch_array($result)) {


echo 'Label 1: ' . $list[0] . '<br>';
echo 'Label 2: ' . $list[1] . '<br><br>';
}

mysqli_close($con);
?>

One option is as good as the other, so you choose which you prefer. Just keep in mind
that when referring back to your code later on, the field names might make more
sense than random numbers.

_____________________________________________________________________________
160 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Summary:

Function Description

Returns the number of affected rows in the previous MySQL


mysqli_affected_rows()
operation

Fetches all result rows as an associative array, a numeric


mysqli_fetch_all()
array, or both

Fetches a result row as an associative, a numeric array, or


mysqli_fetch_array()
both

mysqli_fetch_assoc() Fetches a result row as an associative array

mysqli_num_rows() Returns the number of rows in a result set

Activity-1: (Answer the following questions)


1. Explain Different types of Data Base Operations.

2. What are Mysql functions, explain some of them.

3. How to Display MySQL Table Data.

Activity-2
Perform the below exercise till you are confident.

1. Select data with MySQLi (Object-oriented).

Solution:

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

_____________________________________________________________________________
161 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"]
. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

</body>
</html>

OUTPUT

id: 1 - Name: John Doe


id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley

2. Select data with MySQLi (Object-oriented) and put result in an HTML table

Solution:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
_____________________________________________________________________________
162 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
}
</style>
</head>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " .
$row["lastname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

$conn->close();
?>

</body>
</html>

_____________________________________________________________________________
163 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
OUTPUT

ID Name

1 John Doe

2 Mary Moe

3 Julie Dooley

References
Sr. No References

1. Steven Holzner, S. (2017). ‘ PHP: The Complete Reference’, McGraw Hill Education;
Raunak php study edition.
2. Programming Php, Publisher: Shroff - O'Reilly, Sold By: Orange books
3. ‘PHP Tutorial’ URL:https://www.w3schools.com/php/, (Accessed on 27.12.17)
4. ‘Web Development Tutorial’. URL:http://www.w3resource.com, (Accessed on
27.12.17)
5. Mercer, D. (2004). ‘Beginning PHP5’. Wrox; 1 edition.
6. Greant, Z. (2001). ‘PHP Functions Essential Reference’, Sams Publishing; 1st edition.
7. Naramore, E. , Gerner, J. , Stolz, J. and Glass, M. K. (2005). ‘Beginning PHP5,
Apache, and MySQL Web Development’, Wrox; 2nd edition.
8. McLaughlin, B. (2012). ‘PHP & MySQL: The Missing Manual’, Publisher: O'Reilly
Media.
9. Bacon, J. (2006). ‘Practical PHP and MySQL: Building Eight Dynamic Web
Applications’, Prentice Hall; Pap/Cdr edition .

_____________________________________________________________________________
164 | Web Developments using PHP | PW (Advanced Diploma – SEM I)

You might also like