0% found this document useful (0 votes)
5 views62 pages

First 2 Units PHP

First two units of php programming language

Uploaded by

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

First 2 Units PHP

First two units of php programming language

Uploaded by

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

PROGRAMMING IN PHP

UNIT - I

PHP Definition :

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

 PHP is a recursive acronym for "PHP: Hypertext Pre processor".

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


manage dynamic content, databases, session tracking, even build entire e-commerce
sites.

 It is integrated with a number of popular databases, including My SQL, Post gre


SQL, Oracle, Sybase, Informix, and Microsoft SQL Server.

 PHP is pleasingly zippy in its execution, especially when compiled as an Apache


module on the Unix side. The MySQL server, once started, executes even very
complex queries with huge result sets in record-setting time.

 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and
CORBA), making n-tier development a possibility for the first time.

 PHP is forgiving: PHP language tries to be as forgiving as possible.

PHP code is executed on the server.

What is PHP?

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

What is a PHP File?

 PHP files can contain text, HTML, CSS, JavaScript, and PHP code

SASC - PUDUKKOTTAI Page 1


PROGRAMMING IN PHP

 PHP code is executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"

What Can PHP Do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and even
Flash movies. You can also output any text, such as XHTML and XML.

Why PHP?

 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is easy to learn and runs efficiently on the server side

What's new in PHP 7

 PHP 7 is much faster than the previous popular stable release (PHP 5.6)
 PHP 7 has improved Error Handling
 PHP 7 supports stricter Type Declarations for function arguments
 PHP 7 supports new operators (like the spaceship operator: <=>)

Example :

<!DOCTYPE html>
<html>

SASC - PUDUKKOTTAI Page 2


PROGRAMMING IN PHP

<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>

Output :

My first PHP script!

Common uses of PHP

 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.

 PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.

 You add, delete, modify elements within your database through PHP.

 Access cookies variables and set cookies.

 Using PHP, you can restrict users to access some pages of your website.

 It can encrypt data.

Characteristics of PHP :Five important characteristics make PHP's practical nature possible −

 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

Basic PHP Syntax

A PHP script can be placed anywhere in the document.

SASC - PUDUKKOTTAI Page 3


PROGRAMMING IN PHP

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:

Example

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Output :

My first PHP page

Hello World!

PHP statements end with a semicolon (;).

ESSENTIALS OF PHP :
As of April 2007 there were an estimated 20 million unique web domains actively using PHP
to generate and deliver content. While it is hard to conceptualize 20 million web servers using

SASC - PUDUKKOTTAI Page 4


PROGRAMMING IN PHP

PHP, it is not hard to infer from this number that PHP has taken the web design and
development community by storm since humble beginnings in 1995.
Intended Audience :
It is anticipated that the typical reader already has some web based experience at least in
terms of understanding the concepts of a web server and creating HTML based content.

HISTORY OF THE PHP : The history of PHP is just such a story.

The Creation of PHP :


The first version of what came to be known as PHP was created in 1995 by a man named
Rasmus Lerdof. Rasmus, now an engineer at Yahoo!, needed something to make it easier to
create content on his web site, something that would work well with HTML, yet give him
power and flexibility beyond what HTML could offer him. Essentially, what he needed was
an easy way to write scripts that would run on his web server both to create content, and
handle data being passed back to the server from the web browser. Using the Perl language,
he created some technology that gave him what he needed and decided to call this technology
"Personal Home Page/Forms Interpreter". The technology provided a convenient way to
process web forms and create content. The name "Personal Home Page/Forms Interpreter"
was later shortened to PHP/FI and eventually renamed to represent "PHP: Hypertext
Preprocessor". The name is said to be recursive because the full name also includes the
acronym "PHP" - an odd geeky joke that is common in technology circles when people have
trouble naming things. GNU is another recursive name that represents "GNU's Not Unix".
PHP/FI version 1.0 was never really used outside of Rasmus' own web site. With the
introduction of PHP/FI 2.0 this began to change. When PHP 3 was released in 1997, adoption
of PHP exploded beyond all belief.

PHP 3 - Hits the Big Time :By the time 1997 arrived the number of web sites on the internet
was growing exponentially and most of these web sites were being implemented using the
Apache web server.
It was around this time that Andy Gutmans and Zeev Suraski launched the PHP 3 project, a
project designed to take PHP to the next level.
One of the key achievements of the PHP 3 project was to implement PHP as a robust Apache
Module. PHP 3 was implemented using a modular approach that made it easy for others to

SASC - PUDUKKOTTAI Page 5


PROGRAMMING IN PHP

extend functionality, and also introduced the first elements of object-orientation that would
continue to evolve through subsequent releases.
The combination of PHP 3 and Apache quickly lead to the widespread adoption of PHP, and
it is commonly estimated that, at its peak adoption level, PHP3 was used to power over 10%
of all web sites on the internet.
PHP 4 - Optimization, Scalability and More :With PHP version 4 Andi Gutmans and Zeev
Suraski once again re-architected PHP from the ground up. PHP version 4 was built upon a
piece of technology called the Zend Engine. The move to the Zend Engine brought about a
number of key improvements in PHP:
 Support for other web servers (Microsoft's Internet Information Server (IIS) being of
particular significance).

 Improved memory handling to avoid memory leaks (one of the most difficult types of
problems to isolate in a program).

 Improved efficiency and performance to support large scale, complex, mission critical
enterprise application development using PHP.
 In addition PHP 4 also built on the earlier Object Oriented Programming features of
PHP 3 with the introduction of classes.

PHP 5 - Object Orientation, Error Handling and XML :The main, though far from only,
feature of PHP 5 is the improved support for Object Oriented Programming (OOP). In
addition, PHP 5 introduced some features common in other languages such as Java like
try/catch error and exception handling. PHP 5 also introduced new extensions aimed at easing
the storage and manipulation of data. Significant new features include SimpleXML for
handling XML documents, and SQLite, an embedded basic and easy to use database
interface.
How Popular is PHP?
A quick review of some statistics gives a very clear indication of the phenomenally
widespread use of PHP. A company called Netcraft specializes in recording data about the
types of web servers and web server modules that are used on the internet. As of April 2007
Netcraft reported that PHP was used on over 20,000,000 distinct web domains. A web survey
by SecuritySpace also lists PHP as the most widely deployed Apache module. It is safe to say

SASC - PUDUKKOTTAI Page 6


PROGRAMMING IN PHP

that PHP has taken the internet by storm. As if that wasn't enough one of the world’s most
popular web sites, Wikipedia, is build primarily using PHP.

AN OVERVIEW OF PHP

What Exactly is PHP?


PHP is an intuitive, server side scripting language. Like any other scripting language it allows
developers to build logic into the creation of web page content and handle data returned from
a web browser. PHP also contains a number of extensions that make it easy to interact with
databases, extracting data to be displayed on a web page and storing information entered by a
web site visitor back into the database. PHP consists of a scripting language and an
interpreter. Like other scripting languages, PHP enables web developers to define the
behavior and logic they need in a web page. These scripts are embedded into the HTML
documents that are served by the web server. The interpreter takes the form of a module that
integrates into the web server, converting the scripts into commands the computer then
executes to achieve the results defined in the script by the web developer.

How Does PHP Work?


To develop an understanding of how PHP works it is helpful to first explore what happens
when a web page is served to a user's browser. When a user visits a web site or clicks on a
link on a page the browser sends a request to the web server hosting the site asking for a copy
of the web page. The web server 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.

SASC - PUDUKKOTTAI Page 7


PROGRAMMING IN PHP

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.

The following HTML contains some PHP script that is designed to output an HTML
paragraph tag

<html>

<head>

<title> A PHP Example </title>

</head>

<body>

<?php

Echo ‘<p> This line of HTML generated by a PHP Script embedded into an HTML
document</p>’;

?>

</body>

</html>

The above example looks very much like standard HTML until you reach the part surrounded
by <?php and ?>. These are markers that designate where the embedded PHP script begins
and ends. When the web server finds this it sends it to the PHP module. The PHP module

SASC - PUDUKKOTTAI Page 8


PROGRAMMING IN PHP

interprets it, converts it to HTML and sends it back to the web server. The web server, in
turn, sends the following to the browser:

<html>

<head>

<title> A PHP Example </title>

</head>

<body>

<p> This line of HTML generated by a PHP Script embedded into an HTML document</p>

</body>

</html>

Once loaded into the browser, it is rendered just like any other web page. The fact that the
web page originally contained PHP is completely transparent to the web browser. The above
example is certainly an oversimplification of the power of PHP. Some may question why one
would use PHP to output some static text that could have been achieved more easily using an
HTML tag.

Why is PHP so Useful?


In terms of web page content we have two extremes. At one extreme we have HTML which
is completely static. There is very little that can be done with HTML to create dynamic
content in a web page. At the other extreme we have scripting languages like JavaScript.
JavaScript provides a powerful mechanism for creating interactive and dynamic web pages.
When talking about JavaScript it is important to understand that it is, by design, a client side
scripting language. By this we mean that the script gets executed inside the user's browser
and not on the web server on which the web page originated. Whilst this is fine for many
situations it is often the case that by the time a script reaches the browser it is then either too
late, or inefficient, to do what is needed. A prime example of this involves displaying a web
page which contains some data from a database table. Since the database resides on a server
(either thesame physical server which 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

SASC - PUDUKKOTTAI Page 9


PROGRAMMING IN PHP

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.

PHP OPERATORS :

PHP language supports following type of operators.

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

Lets have a look on all operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by PHP language −

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

Show Examples

Operator Description Example

+ Adds two operands A + B will give


30

- Subtracts second operand from the first A - B will give -

SASC - PUDUKKOTTAI Page 10


PROGRAMMING IN PHP

10

* Multiply both operands A * B will give


200

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer B % A will give


division 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Comparison Operators

There are following comparison operators supported by PHP language

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

Show Examples

Operator Description Example

== Checks if the value of two operands are equal or not, if (A == B) is


yes then condition becomes true. not true.

!= Checks if the value of two operands are equal or not, if (A != B) is


values are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the (A > B) is
value of right operand, if yes then condition becomes not true.

SASC - PUDUKKOTTAI Page 11


PROGRAMMING IN PHP

true.

< Checks if the value of left operand is less than the value (A < B) is
of right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or (A >= B) is


equal to the value of right operand, if yes then condition not true.
becomes true.

<= Checks if the value of left operand is less than or equal (A <= B) is
to the value of right operand, if yes then condition true.
becomes true.

Logical Operators

There are following logical operators supported by PHP language

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

Show Examples

Operator Description Example

and Called Logical AND operator. If both the operands are (A and B) is
true then condition becomes true. true.

or Called Logical OR Operator. If any of the two operands (A or B) is


are non zero then condition becomes true. true.

&& Called Logical AND operator. If both the operands are (A && B) is
non zero then condition becomes true. true.

SASC - PUDUKKOTTAI Page 12


PROGRAMMING IN PHP

|| Called Logical OR Operator. If any of the two operands (A || B) is


are non zero then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the !(A && B)


logical state of its operand. If a condition is true then is false.
Logical NOT operator will make false.

Assignment Operators

There are following assignment operators supported by PHP language −

Show Examples

Operator Description Example

= Simple assignment operator, Assigns values C = A + B will


from right side operands to left side operand assign value of A +
B into C

+= Add AND assignment operator, It adds right C += A is equivalent


operand to the left operand and assign the result to C = C + A
to left operand

-= Subtract AND assignment operator, It subtracts C -= A is equivalent


right operand from the left operand and assign to C = C - A
the result to left operand

*= Multiply AND assignment operator, It C *= A is equivalent


multiplies right operand with the left operand to C = C * A
and assign the result to left operand

SASC - PUDUKKOTTAI Page 13


PROGRAMMING IN PHP

/= Divide AND assignment operator, It divides left C /= A is equivalent


operand with the right operand and assign the to C = C / A
result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent


modulus using two operands and assign the to C = C % A
result to left operand

Conditional Operator

There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
result of the evaluation. The conditional operator has this syntax −

Show Examples

Operator Description Example

?: Conditional If Condition is true ? Then value X : Otherwise


Expression value Y

Operators Categories

All the operators we have discussed above can be categorised 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.

SASC - PUDUKKOTTAI Page 14


PROGRAMMING IN PHP

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left

SASC - PUDUKKOTTAI Page 15


PROGRAMMING IN PHP

PHP STRINGS

A string is a sequence of characters, like "Hello world!".

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

strlen() - Return the Length of a String

The PHP strlen() function returns the length of a string.

Example

<!DOCTYPE html>

<html>

<body>

<?php

echo strlen("Hello world!");

?>

</body>

</html>

OUTPUT : 12

(or)

Return the length of the string "Hello world!":

<?php
echo strlen("Hello world!"); // outputs 12
?>

str_word_count() - Count Words in a String

SASC - PUDUKKOTTAI Page 16


PROGRAMMING IN PHP

The PHP str_word_count() function counts the number of words in a string.

Example

<!DOCTYPE html>

<html>

<body>

<?php

echo str_word_count("Hello world!");

?>

</body>

</html>

OUTPUT : 2

(or)

Count the number of word in the string "Hello world!":

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev() - Reverse a String

The PHP strrev() function reverses a string.

EXAMPLE :

<!DOCTYPE html>

<html>

<body>

SASC - PUDUKKOTTAI Page 17


PROGRAMMING IN PHP

<?php

echo strrev("Hello world!");

?>

</body>

</html>

OUTPUT : !dlrow olleH

(or)

Reverse the string "Hello world!":

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos() - Search For a Text Within a String

The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.

<!DOCTYPE html>
<html>
<body>

<?php
echo strpos("Hello world!", "world");
?>
</body>
</html>
OUTPUT : 6

(or)

SASC - PUDUKKOTTAI Page 18


PROGRAMMING IN PHP

Search for the text "world" in the string "Hello world!":

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The first character position in a string is 0 (not 1).

str_replace() - Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters in a
string.

EXAMPLE :

<!DOCTYPE html>

<html>

<body>

<?php

echo str_replace("world", "Dolly", "Hello world!");

?>

</body>

</html>

OUTPUT : Hello Dolly!

(or)

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

SASC - PUDUKKOTTAI Page 19


PROGRAMMING IN PHP

PHP ARRAYS

An array stores multiple values in one single variable:

EXAMPLE :

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

?>

</body>

</html>

OUTPUT :

I like Volvo, BMW and Toyota.

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

SASC - PUDUKKOTTAI Page 20


PROGRAMMING IN PHP

Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

Get The Length of an Array - The count() Function

The count() function is used to return the length (the number of elements) of an array:

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo count($cars);

?>

</body>

</html>

OUTPUT : 3

PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

SASC - PUDUKKOTTAI Page 21


PROGRAMMING IN PHP

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

EXAMPLE :

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

?>

</body>

</html>

OUTPUT:

I like Volvo, BMW and Toyota.

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like
this:

<!DOCTYPE html>

<html>

SASC - PUDUKKOTTAI Page 22


PROGRAMMING IN PHP

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {

echo $cars[$x];

echo "<br>";

?>

</body>

</html>

OUTPUT:

Volvo
BMW
Toyota

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

SASC - PUDUKKOTTAI Page 23


PROGRAMMING IN PHP

The named keys can then be used in a script:

EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

echo "Peter is " . $age['Peter'] . " years old.";

?>

</body>

</html>

OUTPUT :

Peter is 35 years old.

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop,
like this:

EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

SASC - PUDUKKOTTAI Page 24


PROGRAMMING IN PHP

foreach($age as $x => $x_value) {

echo "Key=" . $x . ", Value=" . $x_value;

echo "<br>";

?>

</body>

</html>

OUTPUT:

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

PHP - Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an
element.

For a two-dimensional array you need two indices to select an element

For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays


of arrays).

First, take a look at the following table:

SASC - PUDUKKOTTAI Page 25


PROGRAMMING IN PHP

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.

To get access to the elements of the $cars array we must point to the two indices (row and
column):

EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array (

SASC - PUDUKKOTTAI Page 26


PROGRAMMING IN PHP

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

?>

</body>

</html>

OUTPUT:

Volvo: In stock: 22, sold: 18.


BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

PHP Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending or


ascending.

PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order

SASC - PUDUKKOTTAI Page 27


PROGRAMMING IN PHP

 asort() - sort associative arrays in ascending order, according to the value


 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort() : The following example sorts the elements of the
$cars array in ascending alphabetical order:

EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

sort($cars);

$clength = count($cars);

for($x = 0; $x < $clength; $x++) {

echo $cars[$x];

echo "<br>";

?>

</body>

</html>

OUTPUT: BMW
Toyota
Volvo

SASC - PUDUKKOTTAI Page 28


PROGRAMMING IN PHP

The following example sorts the elements of the $numbers array in ascending numerical
order:
EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

$numbers = array(4, 6, 2, 22, 11);

sort($numbers);

$arrlength = count($numbers);

for($x = 0; $x < $arrlength; $x++) {

echo $numbers[$x];

echo "<br>";

?>

</body>

</html>

OUTPUT:

2
4
6
11
22

SASC - PUDUKKOTTAI Page 29


PROGRAMMING IN PHP

FLOWCONTROLS IN PHP:

PHP - The if...else Statement

The if...else statement executes some code if a condition is true and another code if that
condition is false.

Syntax

if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

Example

Output "Have a good day!" if the current time is less than 20, and "Have a good night!"
otherwise:

<!DOCTYPE html>

<html>

<body>

<?php

$t = date("H");

if ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

?>

SASC - PUDUKKOTTAI Page 30


PROGRAMMING IN PHP

</body>

</html>

OUTPUT:

Have a good day!

PHP - The if...elseif...else Statement

The if...elseif...else statement executes different codes for more than two conditions.

Syntax

if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}

Example

Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if
the current time is less than 20. Otherwise it will output "Have a good night!":

<!DOCTYPE html>

<html>

<body>

<?php

$t = date("H");

echo "<p>The hour (of the server) is " . $t;

echo ", and will give the following message:</p>";

SASC - PUDUKKOTTAI Page 31


PROGRAMMING IN PHP

if ($t < "10") {

echo "Have a good morning!";

} elseif ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

?>

</body>

</html>

OUTPUT:

The hour (of the server) is 10, and will give the following message:
Have a good day!

PHP switch Statement

The switch statement is used to perform different actions based on different conditions.

The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;

SASC - PUDUKKOTTAI Page 32


PROGRAMMING IN PHP

break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.

EXAMPLE:

<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:

SASC - PUDUKKOTTAI Page 33


PROGRAMMING IN PHP

echo "Your favorite color is neither red, blue, nor green!";


}
?>
</body>
</html>
OUTPUT: Your favorite color is red!

PHP Loops : Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost equal code-lines in
a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain
condition is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The following chapters will explain and give examples of each loop type.

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax

while (condition is true) {


code to be executed;
}

EXAMPLE:

<!DOCTYPE html>

SASC - PUDUKKOTTAI Page 34


PROGRAMMING IN PHP

<html>

<body>

<?php

$x = 1;

while($x <= 5) {

echo "The number is: $x <br>";

$x++;

?>

</body>

</html>

OUTPUT:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

The PHP do...while Loop

The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.

Syntax

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

SASC - PUDUKKOTTAI Page 35


PROGRAMMING IN PHP

EXAMPLE:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>

OUTPUT: The number is: 6

The PHP for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {


code to be executed for each iteration;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

SASC - PUDUKKOTTAI Page 36


PROGRAMMING IN PHP

EXAMPLE:

<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>

OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

PHP Break : It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

<!DOCTYPE html>
<html>

SASC - PUDUKKOTTAI Page 37


PROGRAMMING IN PHP

<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>

OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3

PHP Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";

SASC - PUDUKKOTTAI Page 38


PROGRAMMING IN PHP

}
?>
</body>
</html>

OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9

PHP Functions

The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform a specific task.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

 A function is a block of statements that can be used repeatedly in a program.


 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

SASC - PUDUKKOTTAI Page 39


PROGRAMMING IN PHP

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function:

Syntax

function functionName() {
code to be executed;
}

Note: A function name must start with a letter or an underscore. Function names are NOT
case-sensitive.

EXAMPLE:

<!DOCTYPE html>

<html>

<body>

<?php

function writeMsg() {

echo "Hello world!";

writeMsg();

?>

</body>

</html>

OUTPUT:

Hello world!

SASC - PUDUKKOTTAI Page 40


PROGRAMMING IN PHP

UNIT - II
PHP FUNCTIONS

PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function within Function and Recursive
function also.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like
in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

Syntax

function functionname(){
//code to be executed
}

PHP Functions Example

File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>

Output:
Hello PHP Function

SASC,PUDUKKOTTAI. Page 1
PROGRAMMING IN PHP

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by
comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>

Output:
Hello Sonoo
Hello Sanoo
Hello Vimal
Hello John

Let's see the example to pass two argument in PHP function.

File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>

Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old

SASC,PUDUKKOTTAI. Page 2
PROGRAMMING IN PHP

PHP Call By Reference

Value passed to the function doesn't modify the actual value by default (call by value). But
we can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.

Let's see a simple example of call by reference in PHP.

File: functionref.php

<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Hello Call By Reference

Output:
Hello Call By Reference

PHP Function: Default Argument Value

We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>

SASC,PUDUKKOTTAI. Page 3
PROGRAMMING IN PHP

Output:
Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value

Let's see an example of PHP function that returns value.

File: functiondefaultarg.php

<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>

Output:
Cube of 3 is: 27

PHP Parameterized Function

PHP Parameterized functions are the functions with parameters. You can pass any number of
parameters inside a function. These passed parameters act as variables inside your function.

They are specified inside the parentheses, after the function name.

The output depends upon the dynamic values passed as the parameters into the function.

PHP Parameterized Example

Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two


functions add() and sub().
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>

SASC,PUDUKKOTTAI. Page 4
PROGRAMMING IN PHP

<?php
//Adding two numbers
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
//Subtracting two numbers
function sub($x, $y) {
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</html>

Output:

PHP Call By Value

PHP allows you to call function by value and reference both. In case of PHP call by value,
actual value is not modified if it is modified inside the function.

Example

In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes are
done in the local variable $str2 only. It doesn't reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;

SASC,PUDUKKOTTAI. Page 5
PROGRAMMING IN PHP

?>

Output244Java Tricky Program 23 - Main method signature


Hello

PHP Call By Reference

In case of PHP call by reference, actual value is modified if it is modified inside the function.
In such case, you need to use & (ampersand) symbol with formal arguments. The &
represents reference of the variable.

Example

In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>

Output:29.6M561
This is Call By Reference

PHP Default Argument Values Function

PHP allows you to define C++ style default argument values. In such case, if you don't pass
any value to the function, it will use default argument value.

Example
<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>

SASC,PUDUKKOTTAI. Page 6
PROGRAMMING IN PHP

Output:
Hello Sonoo
Hello Ram
Hello Vimal
PHP Variable Length Argument Function

PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.

The 3 dot concept is implemented for variable length argument since PHP 5.6.

Let's see a simple example of PHP variable length argument function.

<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}

echo add(1, 2, 3, 4);


?>

Output:

10

PHP Recursive Function

PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
EXAMPLE: PRINTING NUMBER
<?php
function display($number) {
if($number<=5){

SASC,PUDUKKOTTAI. Page 7
PROGRAMMING IN PHP

echo "$number <br/>";


display($number+1);
}
}

display(1);
?>

Output:
1
2
3
4
5

What is the Form?


A Document that containing black fields, that the user can fill the data or user can select the
data.Casually the data will store in the data base
READING DATA FROM WEBPAGES
PHP Form Handling

The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form

The example below displays a simple HTML form with two input fields and a submit button:
Example
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

OUTPUT:

SASC,PUDUKKOTTAI. Page 8
PROGRAMMING IN PHP

Name:
E-mail:
Submit

When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.

To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:


Welcome John
Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

OUTPUT:

SASC,PUDUKKOTTAI. Page 9
PROGRAMMING IN PHP

Name:
E-mail:
Submit

and "welcome_get.php" looks like this:


<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.

GET vs. POST

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls
and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which
means that they are always accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to
send. The limitation is about 2000 characters. However, because the variables are displayed
in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?


SASC,PUDUKKOTTAI. Page 10
PROGRAMMING IN PHP

Information sent from a form with the POST method is invisible to others (all names/values
are embedded within the body of the HTTP request) and has no limits on the amount of
information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.

Let's see a simple example to receive data from get request in PHP.4
File: form1.html

1. <form action="welcome.php" method="get">


2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php

1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>

PHP Post Form

Post request is widely used to submit form that have large amount of data such as file upload,
image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You
can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.
File: form1.html

1. <form action="login.php" method="post">


2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
4. <tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>

5. <tr><td colspan="2"><input type="submit" value="login"/> </td></tr>


6. </table>
7. </form>
File: login.php

SASC,PUDUKKOTTAI. Page 11
PROGRAMMING IN PHP

1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password varia
ble
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>

Output:

PHP Form Validation

The HTML form we will be working at in these chapters, contains various input fields:
required and optional text fields, radio buttons, and a submit button:

The validation rules for the form above are as follows:

Field Validation Rules

Name Required. + Must only contain letters and whitespace

SASC,PUDUKKOTTAI. Page 12
PROGRAMMING IN PHP

E-mail Required. + Must contain a valid email address (with @ and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one

First we will look at the plain HTML code for the form:
Text Fields

The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons

The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
The Form Element

The HTML code of the form looks like this:


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
>

When the form is submitted, the form data is sent with method="post".
PHP - Required Fields

From the validation rules table on the previous page, we see that the "Name", "E-mail", and
"Gender" fields are required. These fields cannot be empty and must be filled out in the
HTML form.

SASC,PUDUKKOTTAI. Page 13
PROGRAMMING IN PHP

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @ and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one

PHP - Display The Error Messages

Then in the HTML form, we add a little script after each required field, which generates the
correct error message if needed (that is if the user tries to submit the form without filling out
the required fields):
Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
>

Name: <input type="text" name="name">


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other

SASC,PUDUKKOTTAI. Page 14
PROGRAMMING IN PHP

<span class="error">* <?php echo $genderErr;?></span>


<br><br>
<input type="submit" name="submit" value="Submit">

</form>

PHP Form Validation Example

* required field
Name: *

E-mail: *

Website:

Comment:

Gender: Female Male Other *

Submit

Your Input:

Web Browser
web Browser is an application software that allows us to view and explore information on
the web. User can request for any web page by just entering a URL into address bar.
Web browser can show text, audio, video, animation and more. It is the responsibility of a
web browser to interpret text and commands contained in the web page.
Earlier the web browsers were text-based while now a days graphical-based or voice-based
web browsers are also available. Following are the most common web browser available
today:
Browser Vendor

Internet Explorer Microsoft

Google Chrome Google

SASC,PUDUKKOTTAI. Page 15
PROGRAMMING IN PHP

Mozilla Firefox Mozilla

Netscape Navigator Netscape Communications Corp.

Opera Opera Software

Safari Apple

Sea Monkey Mozilla Foundation

K-meleon K-meleon

PHP BROWSER :

PHP is written as standard text files with the .php extension. PHP files are often saved within
a folder in a web server's public directory (or a web root directory). On most systems this will
either be named public or public_html. For example, if a file was saved as index.php in a
web root directory, a user could access it by
typing http://www.example.org or http://www.example.org/index.php.

PHP and Default Pages (Directory Indexes)


Most PHP and web server setups let you use a file named index.php just as you would use
an index.html file. However, make sure you know which one takes priority so you don't get
unexpected results (usually index.php).

The Request Life-cycle


So what exactly is happening when a user types in the URL http://example.org? When a
user types in http://example.org in a Web client (a browser, for instance), the client issues
a GET request to the server (let's assume that we are both using Apache). When Apache gets
this request, it looks for a file named index.php (or index.html, remember the directory
indexes from earlier?). If a file named index.php is found, Apache essentially says "Hey, this
is a PHP file because it has the .php extension. I am going to give this to the PHP interpreter".

After Apache decides that is is a PHP file, it gives it to the PHP interpreter. When PHP
receives the file it reads through it and executes any PHP code it can find. After it is done
with the file, the PHP interpreter gives the output of the code, if any, back to Apache. When
Apache gets the output back from PHP, it sends that output back to a browser which renders
it to the screen.

PHP And Apache Output


Beginners to PHP programming might often ask questions like "How do I make an image
with PHP?" or "How do I make a text box with PHP?". In all honesty, PHP does neither. In a

SASC,PUDUKKOTTAI. Page 16
PROGRAMMING IN PHP

traditional sense, the main goal of PHP is to generate some HTML document that a browser
can render.

However, modern applications built with client-side MVC frameworks often see the role of
PHP change to just interacting with server-side data storage.

Let's take another look at this process with a diagram. In this diagram, we will assume the
user is going to the Laravel website at http://laravel.com/. The following figure has circled
numbers that will highlight the various stages of the request. A step-by-step explanation of
each step follows the figure.

Step 1
The user enters `http://laravel.com` into their browser and taps/hits 'enter'.
Step 2
After the user has tapped/hit 'enter', the browser sends the page request over the
Internet to the web server.
Step 3
The web server gets the request and analyzes the request information. Apache realizes
that we didn't specify a file, so it looks for a directory index and finds `index.php`.
Step 4
Since Apache knows to send files that end with the `.php` file extension to the PHP
interpreter, it asks PHP to execute the file.
Step 5
In this step, PHP is executing the code contained in the `index.php` file from the
request. During this step, PHP may interact with databases, the file system or make
external API calls, amongst other things.
Step 6
After PHP has finished executing the `index.php` file, it sends the output back to
Apache.
Step 7
Apache receives the output from PHP and sends it back over the Internet to a user's
web browser. This is called the `web response`.

SASC,PUDUKKOTTAI. Page 17
PROGRAMMING IN PHP

Step 8
The user's web browser receives the response from the server, and renders the web
page on a computer or device.

As you can see, PHP interacts with a web server in a very real way. The actual request
process is very simple, and one of the reasons that PHP is so well suited for web application
development.
The PHP programme interacts with the site server, which is the programme that sends out
web pages to the rest of the world. When you type a URL into the address bar of your web
browser, you’re telling the web server at that URL to email you an HTML file. The requested
file is sent by the web server in response. The HTML file is read by your browser, and then
shows the web page. When you press a source on a web page, you’re also requesting a file
from the web server. Additionally, when you press a web page button that submits a form, the
web server processes a file. When PHP is mounted, the procedure is exactly the same. You
submit a file, and the web server, which happens to be running PHP, responds with HTML,
because of PHP it all happens. You can understand this through these steps:-
Step 1 – Client send a page request to the web server.

Step 2 – Web server forwards that request to the PHP interpreter.

SASC,PUDUKKOTTAI. Page 18
PROGRAMMING IN PHP

Step 3 – Now PHP interpreter will take the Date from Database and response it back to the
Web server.

SASC,PUDUKKOTTAI. Page 19
PROGRAMMING IN PHP

Step 4 – At last Web server response to the client who has asked for the page request.

HANDLING POWER IN PHP :


The pow() function in PHP is used to calculate a base raised to the power of exponent. It is
a generic function which can be used with number raised to any value.It takes two
parameters which are the base and exponent and returns the desired answer.
If both the arguments passed are non-negative integers and the result can be represented as
an integer, the result is returned with integer type, otherwise, it is returned as a float.
Syntax:

number pow($base, $exp)

Parameters :

The pow() function accepts two parameters as shown in the above syntax:

$base : It is used to specify the base.

$exponent : It is used to specify the exponent.

Return Value: It returns a number (integer or floating-point) which is equal to $base raised
to the power of $exponent.

Examples:
Input : pow(3, 2)
Output : 9

SASC,PUDUKKOTTAI. Page 20
PROGRAMMING IN PHP

Input : pow(-3, 2)
Output : 9

Input : pow(-3, -3)


Output : 0.037037037037037

Input : pow(-3, -3.2)


Output : NaN

Below programs illustrate the working of pow() in PHP:


When both the parameters passed are positive:

<?php

echo(pow(3, 2));

?>

Output:
9
When the $base is negative and $exponent is a positive even number:

<?php

echo(pow(-3, 2));

?>

Output:
9
When $base is negative and $exponent is a negative odd number:

<?php

echo(pow(-3, -3));

?>

Output:
0.037037037037037

SASC,PUDUKKOTTAI. Page 21
PROGRAMMING IN PHP

When $base is negative and $exponent is a negative number with decimal places:

<?php

echo(pow(-3, -3.2));

?>

Output:
NaN

SASC,PUDUKKOTTAI. Page 22

You might also like