php-pw
php-pw
_____________________________________________________________________________
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.
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.
#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.
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
_____________________________________________________________________________
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.
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.
_____________________________________________________________________________
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.
<!--include /text/header.html-->
<!--getenv HTTP_USER_AGENT-->
<!--endif-->
<!--endif exit-->
Welcome <!--$user-->!<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.
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.
_____________________________________________________________________________
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.
Encapsulation refers to a concept where we encapsulate all the data and member
functions together to form an object.
<?php
class phpClass {
var $var1;
[..]
[..]
?>
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
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
function getPrice(){
function setTitle($par){
$this->title = $par;
function getTitle(){
_____________________________________________________________________________
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.
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.
Following example shows how to set title and prices for the three books by calling
member functions.
$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();
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.
$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->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
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 −
<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.
var $publisher;
function setPublisher($par){
$this->publisher = $par;
function getPublisher(){
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() {
return $this->price;
function getTitle(){
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 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 {
$driver = "SRK";
function __construct($par) {
// is created.
function myPublicFunction() {
return("I'm visible!");
}
_____________________________________________________________________________
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.
class MyClass {
$driver = "SRK";
function __construct($par) {
// is created.
function myPublicFunction() {
return("I'm visible!");
Interfaces
_____________________________________________________________________________
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 {
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.
class MyClass {
function __construct($incomingValue) {
// 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.
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).
<?php
class Foo {
return self::$my_static;
?>
_____________________________________________________________________________
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.
<?php
class BaseClass {
?>
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() {
var $_middleInitial;
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
function toString() {
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.
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.
5. Your scripts are hidden from view. Users only see the HTML output, even when
they view the source.
Install a web server on your own PC, and then install PHP and MySQL
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.
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-2:
Perform the below exercise till you are confident.
_____________________________________________________________________________
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.
<?php
$text = 'PHP Training';
$text = preg_replace('/(\b[a-z])/i','<span
style="color:red;">\1</span>',$text);
echo $text;
?>
<?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.
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:
+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:
0x10 // decimal 16
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
// $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";
Hi, Guido
Hi, $name
Double quotes also support a variety of string escapes, as listed in Table 2-1.
_____________________________________________________________________________
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';
To test whether two strings are equal, use the == comparison operator:
if (is_string($x)) {
// $x is a string
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) { ... }
• The integer 0
_____________________________________________________________________________
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).
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['Toilet'] = "Crapper";
There are several ways to loop across arrays, but the most common is a foreach loop:
_____________________________________________________________________________
41 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "Hello, $name\n";
Hello, Edison
Hello, Wankel
Hello, Crapper
You can sort the elements of an array with the various sort functions:
sort($person);
asort($creator);
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 {
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->name('Crapper');
Hello, Edison
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:
database_query($res);
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";
Use the is_null( ) function to test whether a value is NULL—for instance, to see
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;
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;
_____________________________________________________________________________
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:
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:
The old value of $black is lost. Instead, $black is now another name for the value
$big_long_variable_name = "PHP";
_____________________________________________________________________________
46 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
print "\$short is $short\n";
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";
unset($white);
print $black;
snow
Functions can return values by reference (for example, to avoid copying large strings
$var = "PHP";
return $var;
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.
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++;
$counter = 10;
update_counter( );
update_counter( );
Global counter is 10
Function parameters
As we’ll discuss in more detail in Chapter 3, a function definition can have named
parameters:
_____________________________________________________________________________
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.
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:
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
Arithmetic Operators
There are following arithmetic operators supported by PHP language:
_____________________________________________________________________________
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 -------------------------------------------------------
_____________________________________________________________________________
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>
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>
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.
_____________________________________________________________________________
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
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
?>
_____________________________________________________________________________
61 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
</body>
</html>
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
_____________________________________________________________________________
62 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
$salaries = array(
);
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
?>
</body>
</html>
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(
"chemistry" => 39
),
"chemistry" => 29
),
"chemistry" => 39
);
?>
</body>
</html>
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.
Syntax
if (condition)
else
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")
else
?>
</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")
?>
</body>
</html>
Syntax
if (condition)
elseif (condition)
else
_____________________________________________________________________________
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")
elseif ($d=="Sun")
else
?>
</body>
</html>
Syntax
switch (expression)
case label1:
break;
_____________________________________________________________________________
68 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
case label2:
break;
default:
code to be executed
if expression is different
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":
break;
case "Tue":
break;
case "Wed":
_____________________________________________________________________________
69 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
break;
case "Sun":
break;
default:
?>
</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.
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.
Syntax
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;
$a += 10;
$b += 5;
_____________________________________________________________________________
71 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
?>
</body>
</html>
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:
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>
Loop stopped at i = 10
_____________________________________________________________________________
73 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Syntax
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>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
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>
Loop stopped at i = 3
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-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.
<?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.
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
<?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:
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.
// sin() and asin( ) are the sine and arcsine math functions
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
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:
</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
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).
return $combined_string;
The function takes two arguments, $left and $right. Using the concatenation operator,
in order to cause the function to have a value when it’s evaluated with our arguments,
Because the return statement can accept any expression, even complex ones, we can
_____________________________________________________________________________
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.
<?php
?>
This function takes in an integer, doubles it, and returns the result:
function doubler($value) {
Once the function is defined, you can use it anywhere on the page. For example:
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
_____________________________________________________________________________
81 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
echo "there $b";
outer("well");
inner("reader");
Syntax
function function-name()
statement 1 :
statement 2 :
statement 3 :
......
Elements of a function
A valid function name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores.
Figure 3.1
_____________________________________________________________________________
83 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Figure 3.2
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.
_____________________________________________________________________________
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.
_____________________________________________________________________________
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.
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.
Note: The print() function is not actually a function, so you are not required to use
parentheses with it.
Syntax
print(strings)
Parameter Description
Technical Details
PHP Version: 4+
_____________________________________________________________________________
88 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Example
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
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
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
<?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 ¶
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.
Parameters ¶
what
_____________________________________________________________________________
92 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
phpinfo() options
INFO_CONFIGURATION 4 Current Local and Master values for PHP directives. See
also ini_get().
Return Values ¶
$_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'.
_____________________________________________________________________________
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.
_____________________________________________________________________________
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.
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.
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.
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.
_____________________________________________________________________________
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.
_____________________________________________________________________________
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 ¶
Parameters ¶
number
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 ¶
<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5); // 5 (integer)
echo abs(-5); // 5 (integer)
?>
_____________________________________________________________________________
103 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Description ¶
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
Return Values ¶
Description ¶
Returns the inverse hyperbolic cosine of arg, i.e. the value whose
hyperbolic cosine is arg.
Parameters ¶
arg
Return Values ¶
_____________________________________________________________________________
104 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
exp — Calculates the exponent of e
Description ¶
Note:
'e' is the base of the natural system of logarithms, or approximately
2.718282.
Parameters ¶
arg
Return Values ¶
Examples ¶
<?php
echo exp(5.7);
?>
1.6275E+005
298.87
_____________________________________________________________________________
105 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Working with string functions
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
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
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.
12
_____________________________________________________________________________
107 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
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.
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 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 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 -------------------------------------------------------
When next time browser sends any request to web server then it sends
those cookies.
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.
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.
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.
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 -------------------------------------------------------
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.
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-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.
<?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";
?>
<?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.
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().
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.
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 -------------------------------------------------------
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.
<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>
</form>
<?php
if(isset($_POST['submit'])){
?>
To get value of multiple select option from select tag, name attribute in HTML <select>
tag should be initialize 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>
</form>
<?php
if(isset($_POST['submit'])){
{
_____________________________________________________________________________
123 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
?>
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>
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
?>
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
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.
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.
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:
Then, inside image.php, you can access $_GET['num'] (or $num, if register_globals is
on) to generate the appropriate image.
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 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.
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.
_____________________________________________________________________________
129 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
This will display the following result:
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 -------------------------------------------------------
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>
</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:
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:
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.
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:
_____________________________________________________________________________
137 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
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.
_____________________________________________________________________________
139 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
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.
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.
_____________________________________________________________________________
140 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
Syntax
_____________________________________________________________________________
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.
http://php.net/manual/en/book.errorfunc.php
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.
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).
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()).
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.
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
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 -------------------------------------------------------
Activity-2
Perform the below exercise till you are confident.
1. Write a PHP script that checks if a string contains another string.
<?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.
<?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.
_____________________________________________________________________________
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 .
If you have not created a database then you would need root user and its
password to create a database.
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
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"
;
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:
_____________________________________________________________________________
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:
The 'or die' part is useful as it provides debugging functionality. However, it is not
essential.
mysql_close();
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.
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:
You can't insert more values than the number of fields you have created with the
first query.
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:
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 -------------------------------------------------------
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:
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:
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.
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:
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>
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.
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)); }
_____________________________________________________________________________
158 | Web Developments using PHP | PW (Advanced Diploma – SEM I)
--------------------------------------------------------------- TISS – SVE -------------------------------------------------------
LIKE 'Value 2';");
if (!$update) { die (mysql_error($con)); }
mysqli_close($con);
?>
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.';
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;");
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;");
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
Activity-2
Perform the below exercise till you are confident.
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);
}
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
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);
}
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)