DOC-20241209-WA0009.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

UNIT -I

INTRODUCTION TO PHP
INTRODUCTION TO PHP AND A BRIEF HISTORY OF PHP
PHP started out as a small open source project that evolved as more and more people
found out how usefull it was.
Rasmus Lerdorf unleashed the first version of php way back in 1994.
● PHP is a recursive acronym for “PHP Hypertext Preprossesor”.
● PHP is a server side scripting language that is embedded in HTML . It is used to
manage dynamic content , database ,session tracking , even build entire
e-commerce sites.
● It is integrated with a number of popular databases, including MYSQL,
PostgreSQL, Oracle, Sybase , Informix , and Microsoft SQL Server.
● PHP is pleasingly zippy in its execution , especially when compiled as an apache
module on the unix side. The MYSQL server , once started ,executes even very
complex queries with huge result sets in record – setting time.
● PHP supports a large number of major protocols such as POP3 , IMAP , and
LDAP.PHP4 added support for java and distributed object architechture (COM
and COBRA) making their devlopement a posibilty for the first time.
● PHP is forgiving : PHP language tries to be as forgiving as possible
● PHP syntax is C – like.
Before you continue you should have a basic understanding of the following :
● HTML
● CSS
● Javascript

INSTALLING PHP
After installing the webserver , we need to install PHP it self. It will work together with
the apache webserver we just installed, to allow the webserver to process PHP
documents and return the content to the client . To read more about how this works
,have a look at the introduction chapters . in ase you started Apache before , close it
down now – otherwise the PHP installer might not able to modify the required files!
Start the installation , and proced through it . You will be asked for a location to install
to the default is fine , although you may select another path if you wish too. The first
interesting screen will look like this:
What is PHP ?
● PHP is an actronynmfor “PHP. Hypertext Preprocessor”
● PHP is 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
● PHP code are executed on the server, and the result to the browser as plain
HTML.
● PHP files have extension “.php”.
What does PHP Do ?
● PHP can generate dynamic , page content
● PHP can create , open ,read , write,delete, and close files on the server.+
● PHP can collect from data
● PHP can send and recive cookies.
● PHP can add, delete,modify data in your database.
● PHP can be used to control user-access.
● PHP can encrypt data.
Walk through PHP language Basics:LexicalStuructures
The lexical structure of programming languages is the set of basic rules that governs
how you you write programs in that language . It is the lowest level syntax of the
language and specifies such things as what variable names look like, what characters
are used for commentsband how programs statements are separated from each other.
Case sensitivity
In PHP , all keywords(e.g if , else, while, echo,etc),classes , functions, and
user-defined functions are NOT case-sensitive.
For example , you can write echo construct ways like Echo , ECHO, echo oryou can
write date function like Date,DaTe,date.
// Program to check case sensitivity
<?php
echo “Welcome to PHP”. “<br>”;
ECHO “welcome”. “<br>”;
Echo “php”. “<br>”;
echo Date(“Y/m/d”). “<br>”;
echo DATE(“Y.m.d”). “<br>”;
echo Date(“Y-m-d”);
?>
Output :
Welcome to PHP
welcome
php
2022/10/05
2022.10.05
2022-10-05

You can write pre-defined function in any case let’s take the example of
rand() function
<?php
$random _number=rand();
Echo “<br>Random number = “.
$random_number;
$random_number1=RAND();
Echo “<br>Random number = “.
$random_number1;
$random_number2=Rand();
Echo “<br>Random number = “.
$random_number2;
?>
Output :
Random number = 21438
Random number = 15391
Random number = 15212

in the above example there are three variable named


$random_number,$random_number1, $random_numbe2 and all three hold the rand
function in different case
there will be no error message , all executed properly and give proper result as shown
above.
Whitespace and line breaks
In general, whitespace doesn’t matter in a PHP program. You can spread a statement
across any number lines , or lump a bunch of statements together on a single line.
Forexample this statement:
Raise_prices($inventory,$inflation,$cost_of_living,$greed);
Could just as well be written with more whitespace:
Raise_prices(
$inventory
$inflation
$cost_of_living
$greed);

Or with less whitespace:


Raise_prices($inventory,Inflation,$cost_of_living,$greed);
You can take advantage of this flexible formatting to make your code more readable(by
lining up assignments , indenting, etc)
White space between lines ignored by the PHP that means it’s fine to leave several new
lines.
// PROGRAM FOR WHITE SPACE
<?php
Print “Bye bye”. “<br>”;
//Leaving some blank lines after the PHP code
Print “What’s UP” . “<br>”;
Echo date(“Y-m-d”). “<br>”;
?>
Output :
Bye bye
What’s Up
2022-10-05
You can leave multiple lines in your PHP scripts as shown in the above
example
Comments
A comment in PHP code is a line that is not read/executed as part of the program. Its
only purpose is to be read by someone who is looking at the code.
Comments play very important role at time of development . A comment in PHP code
is short note that PHP engine ignores.
PHP comment is used to provide the short description of our code to the other
developer or for own understanding.
Some Important About PHP Comment
1. Comments are ignored by the browser, but useful for us and as well as other
programmers.
2. It is good programming practice to use the comment.
3. The comment does not show on the browser.
PHP Supports Two-Way Of Commenting
1. Single line comment
2. Multiple line comment
PHP Single Line Comment
Single line comment has two types
1. Using “#”
2. Using “//”
PHP Comment Syntax
// this is comment line
# this is comment line
//PROGRAM FOR PHP SINGLE LINE COMMENT
<?php
echo “Hello welcome to php”. “<br>”;
// comment line
echo”Hello”. “<br>”;
// this is my Second Output Statement
echo date(“Y/m/d”). “<br>”;
#Display current_date
echo date(“Y.m.d”). “<br>”;
// in different format
echo date(“Y-m-d”);
?>
Output:
hello welcome to php
Hello
2022/10/05
2022.10.05
2022-10-05
Comment line will not display on browser and not executed as shown above.

PHP Multiple line comment


Syntax:
/* this is a multiple line comment.
It will not execute.
*/

// PROGRAM FOR PHP MULTIPLE LINE COMMENT


<?php
/*echo “hello welcome to php” . “<br>”;
echo “Hello” . “<br>”;
echo date(“Y/m/d”). “<br>”;
echo date(“Y.m.d”). “<br>”;*/
echo date(“Y-m-d”);
echo “Only two echo will be executed”;
?>
Output:
2018-04-09Only two echo will be executed
You can make comment, any statement, function, variable etc by using /* */ or // or
#.
In the above example from start comment line are not executed and rest of the
statements will execute properly.
Installing and Configuring PHP on Windows
Before start Learning PHP , You Should Have Some Software and their knowledge.
Notepad
Notepad is ASCII(you can say a text editor) editor that is used for writing the PHP
script, many other editors are also available for writing a PHP script like Dreamweaver.
WAMP server or XAMP server
Both servers are used to create run time environment on the client machine
Web browser
The web browser are used for display the output by giving PHP script , for example
Google,Chrome , Firefox, Internet Explorer etc.
How To Install XAMPP Server?
Before installing XAMPP server first I will tell you the need of XAMPP server. PHP is a
server side scripting language so it does not run on the local machine , It runs only on
server so that we need a software that provide the server environment on the local
machine so that XAMPP server is used.
Installation Of XAMPP On Windows
1. Download latest version of XAMPP from XAMPP server
2. Click on XAMPP .exe file that you downloaded, and follow the instructions to
install the application.
3. Click on the next button.

4. Select all the component that is shown in the component window


5. Choose destination folder where you want to install Xampp server.
6. Click on next button
7. Click next button again
8. Now setup is ready to be install
9. Status of the installation , it can be take one or two minutes. It’s totally depend
upon the configuration of the machine.

10. Select check box and click close button.


11.After completion of installation control panel appeard.
12. To start APACHE module click start button that appeared in front of apache
and MYSQL also
13. Type localhost on your browser address bar to launch XAMPP and welcome
page is opened.

Start working with XAMPP


1. Type simple php script on the text editor like notepad ,vscode.
<?php
echo “Welcome to mypage group”;
?>
2. Create new folder on xamp/htdocs/php and save that script inside the folder
with php extension.
Save it :Demo.php
3. Start XAMPP server and type address in any browser.
Localhost/php/Demo.php
Data Types, Variables,Expression and Operators
Variables in PHP
Variables are nothing its just containers that holds data or information . In other, word
variable are just identifiers.
Important Point About PHP Variables
● It’sused for storing information , like name , age, place or anything
● For example 0, you create a variable . like $name and store the value 38.
● The PHP variable names are case-sensitive.
PROGRAM FOR VARIABLES IN PHP
<?php
$variable1=15;
$variable2=38;
$sum=$variable1+$variable2;
echo “First value = “.$variable1.”<br>”;
echo “Second value = “.$variable2. “<br>”;
echo “sum=” .$sum;
?>
Output :
First value =15
Second value = 38
Sum = 53

There are three variables in this example first is “variable1” second is “variable2” and
the third one is “sum” . The value of variables displayed , perform an operation and
store the value of an another named $sum and print.
Example of case sensitive variables
<?php
$a = 7;
$A = 38;
echo $a. “<br>”;
echo $A;
?>
Output
7
38
$a and $A are not same as shown in the above example. Beacause PHP variable name
are case sensitive.
Rules For Variable Decleration
There are some simple rules for creating PHP variable.
● A PHP variable must start with ($) doller sign.
● A valid PHP variable name start with underscore(_) or alphabet.
● The rest of variable name consists of alphanumeric character like acb1.
● PHP variable can any length.
● Uppercase letter is not equal to the lowercase letter.
● Not contain spaces.
PHP Variable Decleration
A variable is a named memory location that contains data that may be manipulated
throughout the execution of the script.
//PHP FOR VARIABLE DECLERATION
<?php
$name = “welcome to php”;
Echo $name;
Echo “<br>”;
$first_value=12.30;
$d1=450;
Echo “The first value :”.$first_value;
Echo “<br>”;
Echo “The second value:”.$d1;?>
Output
Welcome to php
The first value : 12.30
The second value : 450
You can create PHP variable anywhere by using the doller sign in our PHP script.
In this example $name is a string variable , $first_value is the float value and $d1 is a
integer value.
Displaying Variables values
The fastest way to display the variable value , using print_r statement.
$name = “Usha”; $name = “Usha “;
Print_r($name); Echo ($name);

Example of variable Decleration and Initialization


<?php
$var = “Display the value using echo”;
$var1 = “and print_r statements”;
Echo $var.$var1;
Echo “<br>”;
$first_value = 12.30;
Echo $first_value;
$d1=450;
Echo “<br>”;
Print_r($d1);
?>
Output
Display the value using echo and print_r
Statements
12.30
450
Check Type And Length Of Variable
You can use var_dump() function to print data the length of the variable as shown in
below.
//PROGRAM TO USE var_dump()
<?php
$x= “Hello world!”;
$y = “Hello world!”;
$z = 5985;
$w = 10.365;
$names = array (“Usha”, “Supriya”, “Shilpa”);
$p= “hello world”;
$p=null;
Echo $x;
Echo”<br>”;
Echo $y;
Var_dump($z);
Var_dump($w);
Var_dump($names);
Var_dump($p);
?>
Output:
SHello World !
Hello World ! int(5985) floate(10.365) array(3){
[0]=>string(4) “Usha”[1]=> string(7)
“supriya”[2]=> String(6) “Shilpa”}NULL

Data Types
Most of other language like C/C++ and java require specifying what kind of data it can
hold , but in PHP there is no need to specifying data type before using it . All the data
store in PHP variable . Data types are the backbone of any programminglanguage.
<?php
$test=15;
$test1=38;
$mul=$test*$test1;
Echo “First value = “.$test. “<br>”;
Echo “Second value = “.$test1. “<br>”;
Echo “Result =”.$mul;
?>
Output :
First value = 15
Second value = 38
Result = 570

In this example $test, $test1 are the integer type variable , after multiplying the $test
and $test1 stores the value into $mul variable. You can use gettype function tocheck
the data type of the variable.
Data types in PHP Under Various Categories Are Shown Below
● String
● Integer
● Floating point numbers
● Boolean
● Array
● Object
● Null
Hirarchy of Data Types
1. Scaler Data Type
2. Compound Data Type
3. Special Data Type

1. Scaler Data Type


● Scaler data means data that contains only single value
● There are four scaler data types.

All are scaler data types following below


Scaler data Description Example
type
Integers A whole number $a = 38 ;
Float A floating point number $a = 5.50;
Strings Sequence of character $a = “string”;
Boolean Either true or false $a = true;

Integer
An integer is an integral whole number without a decimal point .Integer numbers
are used for counting purpose like 38, 8 etc.
<?php
$x = 5985;
var_dump($x);
?>
Output :int(5985)

Float
Float variables hold fractionalvalues ,like 38.02,7.652 etc it’s used for banking
and financial sector calculation
<?php
$x = 10.365;
var_dump($x);
?>
Output :float(10.365)
String
A string is defined as a character array , like john,caretc .
it’s used for storing array of character.
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output :Hello world!
Hello world!
Boolean
Boolean variables hold true or false.
$x = true;
$y = false;

2. compound data types


Php supports two compound data types , compound data is data that can be
contain more than one values.
All compound data types listed below
Compound data type Description
Array Its holds multiple values
Object A type that may contain properties and remarks

Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the
data type and value:
<?php
$cars
= array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output :
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

Object :
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.
Let's assume we have a class named Car. A Car can have properties like model, color,
etc. We can define variables like $model, $color, and so on, to hold the values of these
properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for
the properties.

If you create a __construct() function, PHP will automatically call this function when
you create an object from a class.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . "" . $this->model . "!";
}
}

$myCar = new Car("black", "Volvo");


echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

Output:
My car is a black Volvo!
My car is a red Toyota!

Special data types


Null data type
● it may contain null as a value.
● It is a special data type

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output :

NULL
● Null is not a string it is a special data type that means does not have any value
you can check by using if-else.

**PHP Operators
Operators are used to perform operations on variables and values .PHP divides the
operators in following groups
● Arithmetic operator
● Assignment operator
● Comparison operator
● Increment /Decrement operator
● Logical operator
● String Operator
● Array operator

PHP Arithmetic Operators


The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Example :
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Substraction $x - $Y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x devided by
$y
** Exponentiation $x ** $y Result of raising $x to the $y
th power

Addition
Example :
<?php
$x = 10;
$y = 6;
echo $x + $y;
?>
Output : 16
Substraction
Example :
<?php
$x = 10;
$y = 6;
echo $x - $y;
?>
Output : 4
Multiplication
Example :
<?php
$x = 10;
$y = 6;
echo $x * $y;
?>
Output : 60

Division
Example:
<?php
$x = 10;
$y = 6;
echo $x / $y;
?>
Output : 1.6666666666667
Modulus
Example :
<?php
$x = 10;
$y = 6;
echo $x % $y;
?>
Output : 4
Exponentiation
Example :
<?php
$x = 10;
$y = 3;
echo $x ** $y;
?>
Output : 1000

AssignmentOperator
The PHP assignmetoperaotor are usedwithnumeric values to write a value to a variable.
The basic assignmetoperator in PHP is = . It meansthat the leftoperandgets set to the
value of the assignment expression on the right.

Assignment Same as Description


x=y x=y The leftoperandgets set to the value of the
expression to the right
x+=y x=x+y Addition
x-=y x=x-y Substraction
x*=y x=x*y Multiplication
x/=y x=x/y Division
x%=y x=x%y Modulus

Example :
<?php
$x = 10;
echo $x;
?>
Output :10
<?php
$x = 20;
$x += 100;
echo $x;
?>
Output :120
<?php
$x = 50;
$x -= 30;
echo $x;
?>
Output : 20
<?php
$x = 5;
$x *= 6;
echo $x;
?>
Output :30
<?php
$x = 10;
$x /= 5;
echo $x;
?>
Output :2
<?php
$x = 15;
$x %= 4;
echo $x;
?>
Output :3
Comparison Operators :
The PHP comparison operators are used to compare two values (number or string):
Example
<?php
$x = 100;
$y = "100";
var_dump($x == $y); // returns true because values are equal
?>
Output : bool(true)

Operator Name Example Result


== Equal $x==$y Returns true if $x is equal to
$y
=== Identical $x===$y Returns true if $x is equal to
$y and they are of the same
type
!= Not equal $x!=$y Return true if $x is not equal to
$Y
<> Not equal $x<>$y Returns true if $x is not equal
to $Y
!== Not identical $x!==$y Returns true if $x is not equl to
$Y or they are not of the same
type
> Greater Than $x>$y Returns true if $x is greater
than $Y
< Less than $x<$y Returns true if $x is less than
$Y
>= Greater than $x>=$y Returns true if $x is greater
or equal to than or equal to $y
<= Less than or $x<=$y Returns true if $x is less than
equal to or equal to $y

<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
Output :bool(false)

<?php
$x = 100;
$y = "100";
var_dump($x != $y); // returns false because values are equal
?>
Output :bool(false)

<?php
$x = 100;
$y = "100";
var_dump($x <> $y); // returns false because values are equal
?>
Output : bool(false)

<?php
$x = 100;
$y = "100";
var_dump($x !== $y); // returns true because types are not equal
?>
Output : bool(true)

<?php
$x = 100;
$y = 50;
var_dump($x > $y); // returns true because $x is greater than $y
?>
Output : bool(true)

<?php
$x = 10;
$y = 50;
var_dump($x < $y); // returns true because $x is less than $y
?>
Output : bool(true)

<?php
$x = 50;
$y = 50;
var_dump($x >= $y); // returns true because $x is greater than or equal to $y
?>
Output : bool(true)

<?php
$x = 50;
$y = 50;
var_dump($x <= $y); // returns true because $x is less than or equal to $y
?>
Output : bool(true)
<?php
$x = 5;
$y = 10;
echo ($x <=> $y); // returns -1 because $x is less than $y
echo "<br>";
$x = 10;
$y = 10;
echo ($x <=> $y); // returns 0 because values are equal
echo "<br>";
$x = 15;
$y = 10;
echo ($x <=> $y); // returns +1 because $x is greater than $y
?>
Output : -1
0
1
Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one,then returns $X

$x++ Post-increment Returns $x , then increments $x by one

--$x Pre-decrement Decrements $x by one , then returns $x

$x-- Post-decrement Returns $x, ten decrements $x by one


Example
Pre-increment
<?php
$x = 10;
echo ++$x;
?>
Output 11

Post-increment
<?php
$x = 10;
echo $x++;
?>
Output 10
Pre-decrement
<?php
$x = 10;
echo --$x;
?>
Output 9

Post-decrement
<?php
$x = 10;
echo $x--;
?>
Output 10

Logical operator
The PHP logical operator are used to combine conditional statements

Operator Name Example Result


And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true,but not
both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

Example
<?php
$x = 100;
$y = 50;
if ($x == 100 and $y == 50) {
echo "Hello world!";
}
Else{
Echo “ Not Equal”;
}
?>
Output : Hello world!

<?php
$x = 100;
$y = 50;
if ($x == 100 or $y == 80) {
echo "Hello world!";
}
?>
Output : Hello world!

<?php
$x = 100;
$y = 50;
if ($x == 100 xor $y == 80) {
echo "Hello world!";
}
?>
Output : Hello world!

<?php
$x = 100;
$y = 50;
if ($x == 100 && $y == 50) {
echo "Hello world!";
}
?>
Output : Hello world!

<?php
$x = 100;
$y = 50;
if ($x == 100 || $y == 80) {
echo "Hello world!";
}
?>
Output : Hello world!

<?php
$x = 100;
if ($x !== 90) {
echo "Hello world!";
}
?>
Output : Hello world!

String Operators
PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1


and $txt2

.= Concatenation $txt1 .= Appends $txt2 to $txt1


assignment $txt2

Example :
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
Output : Hello world!

<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
Output : Hello world!
Array Operators
The PHP array operators are used to compare arrays.
operator Name Example Result
+ Union $x+$y Union of $x and $y
== Equality $x==$y Returns true if $x and $y have
the same key/value pairs
=== Identity $x===$y Returns true if $x and $y have
the same key/value pairs in
the same order and of the
same type
!= Inequality $x!=$y Return true if $x is not equal to
$y
<> Inequality $x<>$y Return true if $x is not equal to
$y
!== Non-identity $x!==$y Return true if $x is not
identical to $y
Example :
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
print_r($x + $y); // union of $x and $y
?>
Output : Array ( [a] => red [b] => green [c] => blue [d] => yellow )

<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x == $y);
?>
Output :bool(false)

<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x === $y);
?>
Output :bool(false)

<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x != $y);
?>
Output :bool(true)

<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x <> $y);
?>
Output :bool(true)
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x !== $y);
?>
Output :bool(true)

FLOW CONTROL STATEMENTS


Conditional statements are used to perform different actions based on different
conditions PHP conditional statements
Theif ,elseif…….else and switch statements are used to take decision based on the
different condition
You can use conditional statements in your code to make you 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.
● Elseif statement – is used with the if…….else statement to execute a set of
code if one of the several condition is 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
Very often wen you write code , you want to perform different actions for
different conditions in PHP we have the following conditional statements
● if statement - executes some code if one condition is true
● if….else statement – executes some code if a condition is true and another
code if that condition is false.
● if…..elseif….else statement – executes different codes for more than two
conditions.
● switch statements – selects one of many blocks of code to be executed.
If statement
If statement executes some code if one condition is true . this is primary decision
making statement in PHP.
Syntax
if (condition)
{
code to be executed if condition is true;
}

<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
?>
Output :Have a good day!

Here , expression is a PHP expression that evaluates to a TRUE OR FALSE value. If


expression is true , the statement that follows is executed if it is FALSE , statement is
not executed
The 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;
}

<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
Else
{
echo "Have a good evening!";
}
?>
Output :Have a good day!

In the above example the condition is not true so that it skips the one line just after
the “if statement” but “else statement” must be executed.
PHP – The if…..elseif….else Statement
The if…..elseif…else statement executes 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 :
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
}
elseif ($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>

The switch statement :


If you want to select one of many blocks of code to be executed , use the switch
statement . the switch statement is used to avoid long blocks of if….else if….else code.
Flow chart of switch case
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different
from all labels;
}

Example
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favoritecolor is red!";
break;
case "blue":
echo "Your favoritecolor is blue!";
break;
case "green":
echo "Your favoritecolor is green!";
break;
default:
echo "Your favoritecolor is neither red, blue, nor green!";
}
?>
Output :Your favoritecolor is red!

PHP Loops
Often when you write
a code, you want the same block of code to run over and over again in a row. Instead
of adding sevral almost equal code_lines in a script , we can use loops to perform a
task line this.
In PHP , we have the following looping statements:
● 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 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 PHP while loop
The expression inside the parenthese is tested ; if it evaluates to true, the code block
inside the braces is executed. Then the expression is tested again if at any point the
expression return false, the loop exists.
● While loop will execute block of code until certain condition is met.
● Function of while loop do a task again and again (as your condition).
Flow Chart

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

Example
<?php
$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>
Output :
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
In the above example, first assign the value of $i=0 and after that checks $i less than
7,if yes , it will be executed first time and check again if it finfd true then again it will
be executed, if any point of time the expression returns fails , the loop will be
terminated
Note :There must use the same expression (that are used in a while condition )in
while loop body otherwise loop will be never terminated. This type of the unterminated
loop is called infinite loop.
The PHP do….while Loop
● A do while loop code block executed at least one time before checking the
expression.
● A do while loop is a modified version of the while loop.
Syntax
do {
code to be executed;
} while (condition is true);

Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output :
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
In above example , the condition is not true instead of data in between do block will be
executed and after that check the condition and loop terminated.
The PHP for loop
A for loop is usually used when the exact number of times a block of code must
execute is known in advance.
The for loop is the easiest way to understand of the PHP loops.
● The initialization state of a variable is setting a loop counter to an initial value.
● It’s involving the relational operator , test the loop counter to determine whether
its value has reached the number of repetations desired.
● Increment or decrement the value of the counter each time.
Syntax
for (init counter; test counter; increment
counter) {
code to be executed for each iteration;
}

Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
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
The PHP foreach Loop
Foreach is a special kind of looping statement that works only on arrays. You can use it
in two wyas . You can either retrive just the value of each element or you can retrive
the element’s key and value.

syntax
foreach ($array as $value) {
code to be executed;
}

Example
1. The following example will output the values of the given array
($colors):
<?php
$colors = array()
?>
Output :
red
green

blue
yellow
2. The following example will output both the keys and the values of the
given array ($age):
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

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


echo "$x = $val<br>";
}
?>
Output :
Peter = 35
Ben = 37
Joe = 43
Embedding PHP in web pages
Although it is possible to write and run standalone PHP programs , most PHP code is
embedded in HTML or XML files . This is,after all , why it was created in the first place.
Processing such documents involves replacing each chunk of PHP n source code with
the output it produces when executed.
Beacause a single file usally contains PHP and non-PHP source code , we need a way
to identify the regions of PHP code to be executed . PHP provides four different ways to
do this.
● The first , and preferred, methods looks like XML.
● The second method looks like SGML
● The third method is based on ASP tags.
● The fourth method uses the standerd HTML with enabled PHP using a regular
HTML editor.
Standered (XML) style
Beacause of advent of the Extensible Markup Language (XML) and the migration of
HTML to an XML language (XHTML), the currently preferred technique for embedding
PHP uses XML – Complaint tags to denote PHP instructions.
The trailing semicolon on the statement is optional , because the end of the block also
forces the end of the expression. Embedded in a complete HTML file , This looks like :
<!doctype html>
<html>
</head>
<title>
This is my first PHP program!
</title>
</head>
<body>
<p>
Look,ma! It’s my first PHP program:<br>
<?php
Echo “Hello World”;
?>
<br>
</p>
</body>
</html>
SGML
Style another style of embedding PHP comes from SGML instruction processing tags.
To use this method ,simply enclose the PHP in .Here’s the “Hello,world”
Example :
<?php
Echo “Hello World”;
?>
This style , known as short tags ,is off by default. Support for short tags can be turned
on by building PHP with the –enable-short tags option, or enable short_open_tag in the
PHP configuration file . The short echo tag, is available regardless of theavailabilty
short tags.
Script style
The final method of distinguishing PHP from HTML involves a tag inverted to allow
client-side scripting within HTML pages, the <script> tag. Since PHP is processed and
removed from the before it reaches the browser, you can use the <script> tag to
surround PHP code.
To use this method , simply specify “php” as the value of thelanguage attribute of the
tag:

<script language = “php”>


Echo “Hello World”
</script>

Installing Lamp(Linux, Apache,MYSQL and PHP) and Linux To Install


Apache,MySQL and PHP.
If you’re a webpage designer or developer and use PHP, mySQL and Apache, you’ll be
needing these applications to be installed.
This will show how to install a LAMP system.LAMP stands for Linux
,Apache,MySQL,PHP.This is intended to help those who have very little knowledge of
using Linux.
Install Apache
To start off we install Apache.
1.Open up theterminal(Applications>Accessories>Terminal).
2.Copy/Paste or type the following line of code into Terminal and then press enter
sudo apt-get install apache2
3.The Terminal will then ask you for you’re password, type it and then
Press enter
Testing Apache
To make sure everything installed correctly we will now test apache to ensure it is
working properly.
1. Open up any web browser and enter the following into the web address:
http:??localhost/
You should see a folder entitled apache2-default/.open it and you will see the
message saying “It works!” congrates to you! Or something like that!

Install PHP
In this page we will install PHP5.
Step1. Again open up the terminal (Applications>Accessories>Terminal).
Step2. Copy /paste or type the following line into terminal and press enter: sudo
apt-get install php5 libapache2-mod-php5
Step3. In order for PHP to work and to be compatible with Apache we must restart
Apache. Sudo /etc/init.d/apache2 restart
Test PHP
To ensure there are no issues with PHP let’s give it a quick test run.
Step1. In the terminal copy/paste or type the following line:
Sudogedit /var/www/testphp.php
This will open up a file called testphp.php.
Step2. Copy/paste this line into the php test file:
<?phpphpinfo();?>
Step3. Save and close the file.
Step4. Now open you’re web browser and type the following into the web address:
http://localhost/testphp.php
(it will show you the page that has all information about your php. If you have prior
experience of installing php in some other OS , you must have seen this page .)
Congrates you have now installed both Apache and PHP.
Install MySQL
To finish this guide up we will install MySQL.
Step1. Once again open up the amazing terminal and then copy/paste or type this line:
sudo apt-get install mysql-server
Step2. (optional) In order for other computers on your network to view the server you
have created , you must first edit the “Bind Address”. Begin by opening up Terminal to
edit the my.cnf file.
Gksudogetdit/etc/mysql/my.cnf
Change the line
Bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.
(In Linux Mint 11, terminal itself asked to the set password , But if it doesn’t follow the
stemp3.)
Step3. This is where things may start to get tricky. Begin by typing the following into
terminal:
Mysql -u root
Following that copy/paste or type this line:
Mysql>SET PASSWORD FOR ‘root’@ ‘localhost’=PASSWORD(‘yourpassword’);
(Make sure to change yourpassword to a password of your choice.)
Step4. We are now going to install a program called phpMyAdmin which is an easy tool
to edit your databases. Copy/Paste or type the following line into terminal.
Sudo apt-get install libaapache-mod-auth-mysql php5-mysql phpMyAdmin
After that is installed our next task is to get PHP to work with MYSQL . To do this we
will need to open a file entitled php.ini. To open it type the following:
Gksudogedit / etc/php5/apache2/php.ini
Now we are going to have to uncomment the following line by taking out the
semicolon(;).
Change this line:
;extension=mysql.so
To look like this:
Extension=mysql.so
Now just restart Apache and you are all set!
Sudo /etc/init.d/apache2 restart.
UNIT II(FUNCTIONS)

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

Functions: Calling a Function


To create a function, you use the following syntax:
<?php
Function function_name(parameter1, parameter2,….){
//Function body code
}

● A function name can be any string that brings with a letter or underscore(_)
followed byzero or one or more letters,underscores and numbers. Function
names are case-insentive . It means count(), Count() and COUNT() refer to the
same function . By convention , PHP built-in functionsare in lowercase.
Inside the brackets () after the function name, you specify one or more parameters. If
a function accepts more than one parameter, each parameter has to be separate by a
comma.
The code inside the curly brace {} is a function body. You can put PHP code, HTML
code or mixed PHP and HTML code inside its body. For Example , the following function
displays the header of web page:
<?php
//defining a function
FunctionToday(){
Echo “Today is Tuesday”;
}
//calling function
Today();
?>

Output :Today is Tuesday


Defining a function
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.

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


<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
Output :Hello world!
Function Parameters and Return Values
1.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.
<?php
function Name($Name) {
echo " Hello $Name.<br>";
}
Name("Dolly");
Name("Neha");
Name("Vanshika");
Name("Payal");
Name("Beauty");
?>
Output :
Hello Dolly
Hello Neha
Hello Vanshika
Hello Payal
Hello Beuty

Let’s see the examples to pass two argument in PHP function.


<?php
function familyName($fname, $year) {
echo "$fnameBorn in $year <br>";
}

familyName("Achal", "1998");
familyName("Mrunali", "1996");
familyName("Shivani", "1999");
?>
Output
Achal born in 1998
Mrunali born in 1996
Shivani born in 1999

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

<?php
FunctionsayHello($name = “Rekha”)
{
Echo “Hello $name<br>”;
}
sayHello(“Mukul”);
sayHello();//passing no value
sayHello(“Karishma”);
?>
Output :
Hello Mukul
Hello Rekha
Hello Karishma

Returning Value
Let’s see an example of PHP function that returns value
<?php
Function cube($n)
{
Return $n*$n*$n;
}
Echo “Cube of 3 is :”
cube(3);
?>
Output
Cube of 3 is : 27

Variable Scope and Variable Functions


In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced /
used.
PHP has three different variable scopes:
● Local
● Global
● Static
1. Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

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


?>

Output :Variable x inside function is:

Variable x outside function is: 5

2. PHP The Static Keyword


Normally, when a function is completed/executed , all of its variables are deleted
. How ever, sometimes we want a local variable NOT to be deleted . We need it
for a further job.
To do this , use the static keyword when you first declare the variable:

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>
Output : 0 1 2

Then each time the function is called, that variablewill still have the information it
contained from the last time the function was called.

Strings: Quoting Strings Constants


Most data you encounter as you program will be sequence of characters or strings.
Strings hold people’s names , passwords , addresses, credit card numbers,
photographs, purchase histories and more . For that reason , PHP has an extensive
selection of functions for workig with strings . this chapter shows the many ways to
write strings in your programs, including the sometimes trickeysubject of interpolation
(placing a variable’s value into a string), then covers functions for changing , quoting
and searching strings .
There are three ways to write a literal strings in your program : using single quotes ,
double quots , and the here document (herdoc) format derived from the unic shell .
These methods differ in wheather they recognize special escape sequences that let you
encode other characters or interpolate variables.
Addcslashes()
Return a string with backlashes in front of the specified characters.
The PHP strings functions are part of PHP core.
Example
Add a backslash in front of the character “w”:

<?php
$str = addcslashes(“Hello World!” ,“W”):
Echo($str);
?>
Output :
Hello \ world!

The addcslashes() function returns a string with backslashes in front of the specified
characters.
Note :The addcslashes() function is case-sensitive.
<?php
$str = “Welcome to my humble Homepage!”;
Echo $str.”<br>”;
Echo addcslashes($str,’m’). “<br>”;
Echo addcslashes($str, ‘H’). “<br>”;
?>
Output
Welcome to my humble Homepage!
Welcome to \my hu\mble Ho\mepage!
Welcome to my humble \Homepage!

Addslashes() Function
Add a backslash in front of each double quote (“):
<?php
$str = addslashes(“What does “yolo”
mean?”);
Echo($str);
?>
Output
What does \”yolo \”mean?

Print() Function
<?php
Print “Hello World!”;
?>
Output : Hello World!

Example : write the value of the string variable ($str) to the output, including HTML
tags
<?php
$str = “Hello World!”;
Print $str;
Print “<br>What a nice
day!”;
?>
Output
Hello World!
What a nice day!

Join two string variables together :


<?php
$str1 = “Hello World”!;
$str2= “What a nice day!”;
Print $str1. “ “ . $str2;
?>
output
Hello world ! What a nice day!

String Concatenation Operator


To concatenate two strings variables together use the dot(.) operator?
<?php
$string1 = “Hey”;
$string2 = “1234”;
Echo $string1. “ “ . $string2;
?>
Output : Hey World 1234
If we look at the code above you see that we used the concatenation operator two
times This is because we had to insert third string.
Between the two stings variables we added a string with a single character , an empty
, space , to separate the two variables.
Using the strlen() Function
The strlen() function is used to find the length of the string.
Let’s find the length of our strimg “Welcome to Maldives!”?
<?php
Echo strlen(“Welcome to Maldives!”);
?>
Output :20
The length of a string is often used in lops or other functions when it is important to
know when the string ends.

using the strpos() function


the strpos() function is used to search for a string or character within a string. If a
match is found in the string, this function will return the position of the first match. If
no match is found, it will return FALSE.
Let’s see if we can find the string “world” in our string ?
<?php
Echo strpos(“Hello world!”,”world”);
?>
Output : 6

As you 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.
Accessing Individual Character
PHP substr() Function
Return “world” from the string
<!DOCTYPE html>
<html>
<body>
<?php
Echo substr(“Hello world”, 6);
?>
</body>
</html>
Output :world

Manipulating and searching string


A string is a sequence of characters , like “ Hello world”
PHP string functions
Some commonly used functions to manipulate strings .
Get the length of the strings
The PHP strlen() function returns the length of the string.
The example below returns the length of the strings “Hello world!”:
<?php
Echo strlen(“Hello world!”);
?>
Output : 12

Count the number of words in a string


The PHP str_word_count() function counts the number of words in a string.
<?php
Echo str_word_count(“Hello world!”);
?>
Output : 2

Reverse a string
The PHP strrev() function reverse a string:
<?php
Echo strrev(“Hello world”);
?>
Output : !dlrowolleH

Replace Text Within a String


The PHP str_replace() function replaces some characters with some other characters in
a strings.
The example below replaces the text “world” with “dolly”
<?php
Echo str_replace(“world” , “Dolly”, “Hello world!”);
?>
Output : Hello Dolly!

Encoding and Escaping


Beause PHP programs often interact with HTMl pages , web addresses , and databases
, there are functions to help you work with those type of data . HTML , web page
addresses and database commands are all strings , but they each require different
chracters to be escaped in different ways . for instance a space in a web address must
be written as %20 , while a literal less-than sign <in an HTML document must be
written as &lt .PHP has a number of built – in functions to convert to and from these
encodings
HTML
Special characters in HTML are represented by entities as &amp; and &lt; There are
two PHP functions that turn special chracters in a string into their entities : one for
removing HTML tags and one for extracting only meta tags.
Entity -quoting all special chracters the htmlentities() function changes all characters
with HTML entity equivalents into those equivalents (with the exception of the space
character). This includes the lessthan sign (<), the greater than (>) the ampersand
(&), and accented chracters
For example
$strings = htmlentities(“EinsturzendeNeubauten”);
Echo $string;
EinsturzendeNeubauten
Entity -quoting only HTML syntax characters
The htmlspecialchars() function converts the smallest set of entities possible to
generate valid HTML . the following entites are coverted:
● Ampersands (&) are converted to &amp
● Double quotes(“) are converted to &quot;
Regular Expresion
Regular expressions are nothing more than a sequence or pattern of chracters itself
they provide the foundation for pattern-matching functionality
Using regular expression you can search a particular string inside a another string ,
you can replace one string by another string and you can split a string into many
chunks .
PHP offres functions specific to two sets of regular expressions functions , each
corresponding to a certain type of regular expression . You can use any of them based
on your comfort
POSIX Regular Expressions
The structure of a POSIX regular expression is not dissimilar to that of a
typicalarithmetic expression: various elements are combined to form more complex
expressions.
The simplest regular expression is one that matches a single character such as g,
inside strings such as g or bag.
Let’s give explaination for few concepts being used in POSIX regular expression . After
that we will introduce you with regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions.They are used to find a range of characters.
Sr No Expression & description
1 [0-9] It matches any decimal digit from o through 9
2 [a-z] It matches any character from lower-case a through
lowercase z.
3 [A-Z] It matches any character from uppercase A through
uppercase Z
4 [a-Z] It matches any character from lowercase a through
uppercase Z.
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
chracters ranging from b through v.
Quantifires
The frequency or position of bracketend character sequence and single chracters can
be denoted by a special character . Each special character having a specific
connotation. The +, * ?,{int . range} , and $ flags all follow a character sequence.
Sr No Expression and Description
1 p+
It matches any string containing at least one p.
2 p+
It matches any string containing zero or more p’s.
3 p?
It matches any string containing zero or more p’s.
4 p{N}
It matches any string containing a sequence of N p’s
5 p{2,3}
It matches any string containing of two or three p’s.
6 p{2,}
It matches any string containing a sequence of atleast two p’s
7 p$
It matches any string with p at the end of it.
8 ^p
It matches any string with p at the beginning of it

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 ?
Sr No Expression & Description
1 [[:alpha:]]
It matches any string containing alphabetic chractersaA through
zZ
2 [[:digit:]]
It matches any string containing numerical numerical digits 0
through 9
3 [[:alnum:]]
It matches any string containing alphanumeric chractersaA
through zZ and 0 through 9
4 [[:space:]]
It matches any string containing space

Comparing Strings
The strcmp() function compares two strings
Note :The strcmp() function is binary – safe and case sensitive.
Syntax
Strcmp(string1, string2)
Parameter Description
String1 Required , specifies the first string to compare
String2 Required , specifies the second string to compare
Return This function returns:
Value ● 0 -if two strings are equal
● <0-if string 1 is less than string2
● >0 -if string 1 is greater than string2

Compare two strings (case-sensitive = Hello and hELLO will not output
the same):
<?php
Echo strcmp(“Hello” , “Hello”);
Echo “<br>”;
Echo strcmp(“Hello” , “hELLO”);
?>
Output : 0
-1

Cleaning Strings
Often the strings we get from files or users need not to be cleaned up before we can
use them. Two common problems with raw data are the presence of extraneous
whitespace,and incorrect capitalization (uppercase verses lowercase)

Removing Whitespace
You can remove leading or trailing whitespace with the trim(), ltrim(),and rtrim()
functions
$trimmed = trim(string[,charlist]);
$trimmed = ltrim(string[,charlist]);
$trimmed = rtrim(string[,charlist]);
Trim() returns a copy of strings with whitespace removed from the beginning and the
end. ltrim() does the same , but removes whitespace only from the start of the string.
rtrim() removes whitespace only from the end of the string . The optionalcharlist
argument is a string that specifies all the characters to strip. The default characters to
strip are given in table
Table : Default characters removed by trim(), ltrim(), and rtrim()
Character ASCII value Meaning
““ 0x20 Space
“\t” 0x09 Tab
“\n” 0x0A Newline (line feed)
“\0” 0x00 Nul-byte
“\x0B” 0x0B Vertical tab

For Example
$title = “Programming in PHP \n”;
$str_1=ltrim($title);
$str_2=rtrim($title);
$str_3=trim($title);
Given a line of tab-seperated data, use the charset argument to remove leading or
trailing whitespace without deleting the tabs :
$record = “Fred\tFlintstone\t35\tWima \n”;
$record = trim($record, “\r\n\0\x0B”;
//$record is “Fred\tFlinstone\t35\tWilma”
Changing Case
PHP has sevral functions for changing the case of string :strtolower () and strtoupper
() operate on entire strings , ucfirst() operates only on the first character of the string ,
and ucwords() Operates on the first character of each word in the string . Each
function takes a string to operate on as an arguent and returns a copy of that string ,
appropriately changed
For example :
$string1 = “FRED flintstone”;
$string2 = “barney rubble”;
Print(strtolower($string1));
Print(strtoupper($string1));
Print(ucfirst($string2));
Print(ucwords($string2));
Output :
Fredflintstone
FRED FLINSTONE
Barney rubble
Barney Rubble
If you’ve got a mixed string that you want to convert to “title case” where the first
letter of each word is in uppercase and the rest of the letters are in lowercase , use a
combination of strtolower() and ucwords():
Print(ucwords(strtolower(string1)));
Fred Flintstone
PHP’s Regexp PERL Compatible Functions
PHP offers following functions for searching strings using perl-compatible regular
expressions?
Sr.No Function & Description
1 Preg_match()
The preg_match function searches string for pattern,
returning true if pattern exists and false otherwise.
2 Preg_match_all()
The preg_match_all() function matches all occurrences of
pattern in string.
3 Preg_replace()
The preg_replace() function operates just like preg_replace(),
except that regular expressions can be used in the pattern
and replacement input parameters.

Example :
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
Output : 1
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
Output :4
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>
Output :Visit W3Schools!
Modifiers
several modifiers are available that can make your work with regexps much easier ,
like case sensitivity , searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
o Evaluates the expression only once
s Allows use of to match a newline character
x Allows you to use white space in the expression for clarity
g Globallyfinds all matches
cg Allows a search to continue even after a global match fails

UNIT-III (ARRAYS)
Introduction
An array in PHP is actually an ordered map. A map is a type that associates values to
keys. This type is optimized for several different uses; It can be treated as an array.
List, hash table, dictionary, collection, stack, queue and probably more.
PHP array are more like hash maps in other languages. They have a set of “keys”
which can be strings or integers and each key has a value associated with it, if all keys
are integers and are consecutive numbers, PHP arrays behave similar to real arrays,
except that their size is not fixed. But if the keys are out of order, or some keys are
strings, PHP arrays behave more like hash maps.
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 student names, for example), storing the student name in
single variables could look like this :
$names1 = “Ketki”;
$names2 = “Asha”;
$names3 = “Bhakti”;
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 contained one or more arrays
**PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$names = array(“Ketki”, “Aasha”, “Bhakti”);
Or the index can be assigned manually:
$names[0] = “Ketki”;
$names[1] = “Aasha”;
$names[2] = “Bhakti”;
The following example creates an indexed array named $student, assigns three
elements to it and then prints a text containing the array values:
<html>
<body>
<?php
$names = array (“Ketki”, “Aasha”, “Bhakti”);
Echo “I like” . $names[0]. ”, “.$names[1]. “and” . $names[2]. “.”;
?>
</body>
</html>
Output : 3

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:
<html>
<body>
<?php
$names = array(“Ketki”, “Aasha”, “Bhakti”);
$arrlength = count($names);
For($x=0 ; $x < $arrlength ; $x++){
Echo $names[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output:

Ketki
Aasha
Bhakti
Get The Length of an Array – The count() Function
The count() functions is used to return the length (the number of elements) of an
array:
<html>
<body>
<?php
$names = array(“Ketki” , “Aasha”, “Bhakti”);
Echo count($names);
?>
</body>
</html>
Output: 3

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”;
The named keys can then be used in script:
<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:
<html>
<body>
<?php
$age = array(“Peter”=> “35”, “Ben”=> “37”, “Joe”=> “43”);
Foreach($age as $key =>$value)
{
Echo “Key=” .$key.” , “Value= “. $value;
Echo “<br>”;
?>
</body>
</html>
Output :
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending
or ascending.
PHP – Sort functions for Arrays
The following PHP array sort function:
● sort() – sort arrays in ascending order
● rsort() – sort arrays in descending order
● asort() – sort associative arrays in ascending order, according to the value
● ksort() – sort associative arrays in ascending order , according to the value
● 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 $names array in ascending
alphabetical order:
<html>
<body>
<?php
$names = array(“Ketki”, “Aasha”, “Bhakti”);
Sort($names);
$clength = count($names);
For($x=0; $x<$clength; $x++){
Echo $names[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output
Aasha
Bhakti
Ketki

The following example sorts the elements of the $numbers array in ascending
numerical order:
<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
Sort Array in Descending Order – rsort()
The following example sorts the elements of the $names array in descending
alphabetical order:
<html>
<body>
<?php
$names = array(“Ketki”, “Aasha”, “Bhakti”);
rsort($names);
$clength = count($names);
For($x=0; $x < $clength; $x++)
{
Echo $names[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output
Ketki
Bhakti
Aasha

The following example sorts the elements of the $numbers array in descending
numerical order:
<html>
<body>
<?php
$numbers = array(4,6,2,22,11);
rsort($numbers);
$arrlength = count($numbers);
For($x=0 ; $x < $arrlength ; $x++)
{
Echo $numbers[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output
22
11
6
4
2
Sort Array (Ascending Order),According to Value – asort()
The following example sorts an associative array in ascending to the value:
<html>
<body>
<?php
$age = array(“Peter”=> “35”, “Ben”=> “37”, “Joe”=> “43”);
asort($age);
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
Sort Array (Ascending Order), According to Key – ksort()
The following example sorts an associative array in ascending order, according to the
key:
<html>
<body>
<?php
$age= array(“Peter”=> “35”, “Ben”=> “37” , “Joe”=> “43”);
Ksort($age);
Foreach($age as $x => $x_value)
{
Echo “Key=”. $x .”, Value=” .$x_value;
Echo “<br>”;
}
?>
</body>
</html>
Output
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

Sort Array(Descending Order),According to Value – arsort()


The following example sorts an associative array in descending order, according to the
value:
<html>
<body>
<?php
$age = array(“Peter”=> “35” , “Ben”=> “37”, “Joe”=> “43”);
Arsort($age);
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
Sort Array (Descending Order),According to Key – krsort()
The following example sorts an associative array in descending order, according to the
key:
<html>
<body>
<?php
$age=array(“Peter”= “35”, “Ben”=> “37”, “Joe”=> “43”);
Krsort($age);
Foreach($age as $x => $x_value)
{
Echo “Key=” .$x. “,Value=” . $x_value;
Echo “<br>”;
}
?>
</body>
</html>
Output :
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37

PHP - Multidimensional Array


A multidimensional array is an array containing one or more arrays.
PHP understands 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.
PHP – Two -dimensional Arrays
a two-dimensional array is an array of arrays (a three- dimensional array is an array of
arrays of arrays).
Name Stock Sold
Audi 22 18
BMW 15 13
Verna 5 2
Range Rover 17 15

First, take a look at the following table:


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

<?php
$cars = array (
array("Audi",22,18),
array("BMW",15,13),
array("Verna",5,2),
array("Rang 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
Audi: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Verna: In stock: 5, sold: 2.
Rang Rover: In stock: 17, sold: 15.
Extracting Multiple Values
To copy all of an array’s values into variables, use the list() construct:
List($variable,….)=$array;
The array’s values are copied into the listed variables, in the array’s internal order. By
default that’s the order in which they were inserted, but the sort functions described
later let you change that. Here’s an example:
$person = array(‘name’ => ‘Fred’ , ‘age’=> 35 , ‘wife’=> ‘Betty’);
List($n,$a,$w) = $person; //$n is ‘Fred’, $a is 35 , $w is ‘Betty’
If you have more values in the array than in the list(), the extra values are
ignored :
$person = array(‘name’=> ‘Fred’ , ‘age’=> 35 , ‘wife’=> ‘Betty’);
List($n, $a) =$person; //$n is ‘Fred’, $a is 35
If you have more values in the list() than in the array, the extra values are set
to NULL:
$values= array(‘hello’,’world’);
List($a, $b, $c) = $values // $a is ‘hello’,$b is ‘world’,$c is NULL
Two or more consecutive commas in the list() skip values in the array:
$values = range(‘a’, ‘e’);
List($m,,$n,,$o)=$values; //$m is ‘a’,$n is ‘c’, $o is ‘e’

Slicing an Array
To extract only a subset of the array, use the array_slice() function:
$subset = array_slice(array, offset, length);
The array _slice() function returns a new array consisting of a consecutive series of
values from the original array. The offset parameter identifies the initial element of
copy and the length para meter identifies the number of values to copy. The new array
consecutive numeric keys starting at 0.
For example
<?php
$a=array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a,2));
?>
OUTPUT
Array ( [0] => blue [1] => yellow [2] => brown )

Splitting an Array into Chunks


To divide an array into smaller, evenly sized arrays, use the array_chunk() function:
Syntax: array_chunk(array, size, preserve_key)
The function returns an array of the smaller arrays. The third argument,
preserve_keys, is a Boolean value that determines weather the elements of the new
arrays have the same keys as in the original or new numeric keys starting from 0 . The
default is to assign new keys,as shown here:
Example :
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>
OUTPUT:
Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] => Toyota [1]
=> Honda ) [2] => Array ( [0] => Mercedes [1] => Opel ) )

Keys and Values


The array_keys() function returns an array consisting of only the keys in the
array, in internal order:
Syntax :$array_of_keys = array_keys(arrayname);
Here’s an example:
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>
OUTPUT
Array ( [0] => Volvo [1] => BMW [2] => Toyota )
PHP also provides a (less generally useful) function to retrive an array of just
the values in an array, array_values():
$array_of_values =array_values(array name);
As with array_keys(), the values are returned in the array’s internal order.
Here’s an example:
<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>
OUTPUT :
Array ( [0] => Peter [1] => 41 [2] => USA )

Cheacking whether an Element Exists


To see if an element exists in the array, use the array_key_exists(key,arrary) function:
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
OUTPUT:
Key exists!
Removing and Inserting Elements in an array
The array_splice() function can remove or insert elements in an array:
$removed = array_splice(array, start ,length ,replacement);
We’ll look at array_splice() using this array:
$subjects = array(‘physics’, ‘chem’, ‘maths’, ‘bio’, ‘cs’, ‘drama’, ‘classics’);
We can remove the math , bio, and CS elements by telling array_splice() to
start at position 2 and remove 3 elements:

$removed = array_splice($subjects ,2,7,5);


//$removed is array(‘math’, ‘bio’, ‘cs’)
//$subjects is array(‘physics’, ‘chem’):

Creating variables from an array


The extract() function automatically creates local variable from an array. The indexes
of the array elements are the variables names:
If a variable created by the extraction has the same name as an existing one, the
extracted variable overwrites the existing variable
Example :
<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "i= $a; j = $b; k = $c";
?>
OUTPUT:i= Cat; j = Dog; k= Horse

Creating an Array from Variables


The compact() function is the complement of extract(). Pass it the variable names to
compact either as separate parameters or in an array. The compact() function creates
an associative array whose keys are the variables name and whose values are the
variable’s values. Any names in the array that do not correspond to actual variables
are skipped here’s an example of compact() in action:
Example :
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
OUTPUT: Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )

Traversing Arrays
The most common task with arrays is to do something with every element-for
instance, sending mail to each element of an array of address, updating each file in an
array of filenames, or adding up each element of an array of prices. There are sevral
ways to traverse arrays in PHP, and the one you choose will depend on you data and
the task you’re performing.
The foreach Construct
The most common way to loop over elements of an array is to use the foreach
construct:
<?php
$address = array(“@raisoni.net”, “[email protected]”);
Foreach ($address as $value)
{
echo “Processing {$value}\n”;
}
?>
OUTPUT:
Processing { @raisoni.net}
Processing { [email protected]}

PHP executes the body of the loop (the echo statement) once for each element of
$addresses in turn, with $value set to the current element. Elements are processed by
their internal order.

An alternative form of foreach gives you access to the current key:


<?php
$person = array (‘name’ => “Max”, ‘age’=> 40, ‘wife’=> “glory”);
Foreach ($person as $key => $value)
{
Echo “Fred’s {$key} is {$value}<br>”;
}
?>
OUTPUT:
Fred’s name is Max
Fred’s age is 40
Fred’s wife is glory

In this case, the key foreach element is placed in $key and the corresponding value is
placed in $value.
The foreach construct does not operate on the array itself, but rather on a copy of it .
You can insert or delete elements in the body of a foreach loop, safe in the knowledge
that the loop won’t attempt to process the deleted or inserted elements.
Acting on entire arrays
Arrays is a kind of data type will almost certainly be used by the PHP programmers as
its flexibility to accommodate data. The array can also hold dozens or even hundreds of
data.
The topic about array is very very wide.
Writing Array in PHP
In PHP, we can define an array in two ways, by using the array function array() or
simply use a square bracket[].
<?php
$vehicle = [];//since PHP 5.4
$vehicle = array(); //All version of PHP

Indexed Array and Associative Array


Array in PHP can be divided into two types :
1) indexed Array and
2) Associative Array
Indexed array mean that the keys of the array are sequence numbers such as the
example in the above figure Example:
<?php
$vehicle = [‘car’, ‘Motorcycle’, ‘Bicycle’, ‘Truck’, ‘Bus’];
echo ‘<pre>’;
print_r($vehicle);
?>
/*Result:
Array
(
[0] => car
[1] => Motorcycle
[2] => Bicycle
[3] => Truck
[4] => Bus
)*/
In the example above , we know that the index(key) is starting from the number of 0
then followed by 1,2 , etc…….0 for car ,1 for Motorcycle etc……
We can change the initial numbers of the index into 1 , for example:
$vehicle = [ 1 => ‘car’ , ‘Motorcycle’, ‘Bicycle’, ‘Truck’, ‘Bus’];
/*Result:
Array
(
[1] => car
[2] => Motorcycle
[3] => Bicycle
[4] => Truck
[5] => Bus
)*/
Note that the initial number of the index only allowed to use 0 or 1.
Key and Value In Array
Array always consists of keys and either for indexed array or associative array. The
term of key is important because we always use it to call the value of the array.
The key is always located on the left side and the value is always located on the right
side.
For example(taken from the previous):
$user = [‘id’=> 786, ‘pass’=> 123, ‘role’=> ‘admin’];
In the above example , the $user variable contains an array , with its keys are: id ,
pass and role , while its values are : 786 , 123, and admin
While for the indexed array , the key is a sequence number which is by default starts
from zero . Consider the following example:
$vehicle = [‘car’, ‘Motorcycle’, 5 => ‘Bicycle’, ‘Truck’, ‘Bus’];
Echo ‘<pre>’;
print_r($vehicle);
/*Result
Array
(
[0] => car
[1] => Motorcycle
[5] => Bicycle
[6] => Truck
[7] => Bus
)*/
Although it is not stated explicitly , when we print out the array , the key of array is
showed up.

Add/Remove Element of Array in PHP


To add an element to the array, simply define a variable/constant followed by a square
bracket (either contain a key or not ), for example:
Examples foran associative array:
<?php
$car = [‘merk’ => ‘Toyota’, ‘type’ => ‘Vios’, ‘Year’ => 2016];
$car[‘color’] = ‘Silver’;
Echo ‘<pre>’;
Print_r($car);
?>
OUTPUT:
Array
(
[merk] => Toyota
[type] =>Vios
[year] => 2016
[color] =>Silver
)
Further more, there are many functions to add elements to the array.
Deleting array element
There are two functions to remove the element of the array, that are: unset and
array_slice using unset to remove element of array
We can use unset if we already know the key of the array, for example:
//Associative array
<?php
$car = [‘merk’ => ‘Toyota’, ‘type’ => ‘Vios’, ‘year’ => 2016];
Unset($car[‘type’]);
Echo ‘<pre>’;
Print_r($car);
?>
OUTPUT:
Array
(
[merk] => Toyota
[year] => 2016
)

Indexed array
<?php
$vehicle = [‘car’, ‘Motorcycle’, ‘Bicycle’, ‘Truck’, ‘Bus’];
Unset($vehicle[0]);
Echo ‘<pre>’;
Print_r($vehicle);
?>
OUTPUT:
Array
(
[1] => Motorcycle
[2] => Bicycle
[3] => Truck
[4] => Bus
)

UNIT-IV(Reading data in Web Pages)

Reading data in web pages : setting Up web pages to communicate with PHP
Introduction
To connect to PHP on the server or any code on the server, to set up web pages a
particular way. To enclose all HTML controls in an HTML form, and have to indicate in
that form where the data in those controls will be sent.
For example, the user might enter their name in a text field, and have to let the
browser know where to send that name in a text field,and have to let the browser
know where to send that name when the user clicks the submit button
HTML forms might be
<form>
.
.
.
</form>

It’s compulsory to specify the method with which data will be sent- the two most
common methods are “get” and “post” and might choose the get method here:

<form method=”get”>
.
.
.
</form>
<form method= “post”>
.
.
.
</form>

To create a submit button- note it has to be inside the HTML <form> element – with
the caption send, and that are use an <input> element with the type attribute set to
“submit” To create submit button.
<html>
<head>
<title>connecting to PHP
</title>
</head>
<body>
<h1> Connecting to PHP </h1>

HANDLING TEXT FIELD


You have but together a web page, html, that has a text tied and a submit button in a
form.
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>entering data into text field</h1>
<form method= "get">
name :<input type="text" name="name">
email id: <input type="text" name="email">
<input type="submit" value="send">
</form>

<?php
echo "your name is:";
echo $_REQUEST["name"];
echo "<br>";
echo "and email id is:";
echo $_REQUEST["email"];
?>

</body>
</html>

All this PHP script , does is to echo the name the user entered into the datatext field.
HANDELING TEXTAREAS
Text fields are fine if you want a single line of text, but if you want multiline text input,
you have to go with text areas.
Here’s an example, .html that presents the user with a text area, and asks what pizza
toppings they want. It starts like this:

<html>
<head>
<title>Document</title>
</head>
<body>
<h1>entering data into text areas</h1>
<form method= "post">
<textarea name="data" cols="50" rows="5">
1.
2.
3.
4.
</textarea>
<br>
<input type="submit" value= "send">
</form>
<h1>You ordered pizza with</h1>
<?php
$text = $_REQUEST["data"];
echo $text;
?>
</body>
</html>

Check Boxes
The next steps up in controls are check boxes- those square controls that you can
select or de-select with the mouse
You create check boxes with the <input> element like this in a web page, where you’re
asking the user if they want fries in .htm
<html >
<head>
<title>Document</title>
</head>
<body>
<h1>Enter data into checkbox</h1>
<form method = "post">
Do you want fries?
<input name="check" type = "checkbox" value = "Yes">
Yes
<input name="check1" type = "checkbox" value = "No">
No
<br>
<br>
<input type="submit" value = "send">
</form>
selected:
<?php
if(isset($_REQUEST["check"]))
{
echo $_REQUEST["check"],"<br>";
}
if(isset($_REQUEST["check1"]))
{
echo $_REQUEST["check1"],"<br>";
}
?>
</body>
</html>
</body>
</html>

You can see the result in above fig, where you’re reading what check boxes the user
selected
Note that the user could click both check boxes here- which would mean that they both
wanted fries and didn’t want fries. A better choice for the controls here are radio
buttons, where only one can be selected at a time, and they’re coming up next.

HANDLING RADIO BUTTONS


Check boxes are good if you want the user to be able to select multiple items from a
number of choices. But if you want to let the user select only one item from a number
of choices, you should use radio buttons instead, because they only allow the user to
make one selection at a time.
Here is an example, html , that like the preceding example , asks the user if they
want fries-but unlike the previous example, this time , the user can only select yes or
no, not both
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Radio button
</title>
<body>
<h1>Enter radio buttons</h1>
<form method = "post">
Do you want fries?
<input name="radio" type = "radio" value = "Yes">
Yes
<input name="radio" type = "radio" value = "No">
No
<br>
<br>
<input type="submit" value = "send">
</form>
selected:
<?php
if(isset($_REQUEST["radio"]))
{
echo $_REQUEST["radio"];
}
else
{
echo "No radio button was selected.<br>";
}
?>
</body>
</html>

Handling List Boxes


List boxes are also common HTML control, and they take a little special handling. If
you wanted to let the user select their favorite of ice cream; in listbox.html, where you
are creating the list box with a <select> HTML control.
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<h1>Enter data in list box</h1>
select your favoriteicecreamflavors:
<form method= "post">
<select name="ice_cream[]" multiple>
<option>vanilla</option>
<option>chocolate</option>
<option>butterscoch</option>
<option>strawbery</option>
</select>
<br>
<br>
<input type="submit" value="send">
</form>
your icecreamfalvors are:
<br>
<?php
foreach($_REQUEST["ice_cream"]as$flavor){
echo $flavor,"<br>";
}

?>
</body>
</html>

Password Controls
A common use of PHP is to check password on the server, giving the user access to a
resource if they have the right password, and you can use password controls for that
here’s an example that asks the user for their password.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h3>Enter data</h3>
<form method="post">
<input name="password" type="password">
Enter password
<br>
<input type="submit" value="send">
</form>
<?php
if($_REQUEST["password"]=="letmein")
{
echo "password accepted";
}
?>
</body>
</html>

Handling Image Map


You can also handle image maps-those clickable images you see in the browsers-with
PHP, although doing so takes a little extra effort.
You can see an image map example in imagemap.html, which uses an <input type=
“image”> element to display an image map:
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>Enter image data </h1>
<form method = "post">
click the image:
<br>
<input type="image" name= "imap"src=”uploads/img/artban1.jpg">
You clicked the image map at:
<?php
echo $_REQUEST["imap_x"],$_REQUEST["imap_y"];
?>
</form>
</body>
</html>
Handling Hidden Controls
HTML hidden controls are a good match for PHP scripts , beacause they let you store
data in web pages that the user doesn’t usually see, and that you can make use of on
the server
Here is an example that uses a hiden control named customer_type to store what we
think of the customer, behind the scenes. In this case, phphidden.php, customer_type
is set to “good”:

<html>
<head>
<title>Document</title>
</head>
<body>
<h1>Storing data with hidden controls</h1>
what kind of customer do we think you are?
<br>
click the button to find out.
<br>
<form method= "post">
<input name="customer_type" type="hidden" value="good">
<br>
<br>
<input type="submit" value="send">
</form>
<h1>Reading data from password controls</h1>
we think you are a
<?php
echo $_REQUEST["customer_type"];
?>
customer.
</body>
</html>
You can see the result in above figure the customer is a good customer.
Hidden controls like this are popular for storing information about the user for use with
PHP-another popular for storing information about the user is to use cookies.
Handling File Uploads
A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for
file uploads as upload_tmp_dir and the maximum permitted sixe of files that can be
uploaded is stated as upload_max_filesize . These parameters are set into PHP
configuration file php.ini
The process of uploading a file follows these steps?
● The user opens the page containing a HTML form featuring a text files, a browse
button and a submit button.
● The user clicks the browse button and selects a file to upload from the local PC.
● The full path to the selected file appears in the text filed then the user clicks the
submit button.
● The selected file is sent to the temporary directory on the server.
● The PHP script that was specified as the form handler in the form’s action
attribute checks that the file has arrived and then copies the file into an
intended directory.
● The PHP script confirms the successto the user.
As usual when writing files it is necessary for both temporary and final locations to
have permissions set that enable file writing’ if either is set to be read-only then
process will fail. An uploaded file could be a text file or image file or any document.
Creating an upload form
The following HTML code below creates an uploader form. This form is having method
atrribute set to post and enctype attribute is set to maultipart/form-data
Creating an upload script
There is one global PHP variables called $_FILES.This variable is an associated double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input’s name attribute in uploading form was file, then PHP would
create following five variables?
● $_FILES[‘file’][tmp_name’] – the uploaded file I the temporary directory on
the web server.
● $_FILES[‘file’][‘name’] – the actual name of the uploaded file.
● $_FILES[‘file’][‘size’] – the size in bytes of the uploaded file.
● $_FILES[‘file’][‘type’] – the MIME type of the uploaded file
● $_FILES[‘file’][‘error’] – the error code associated with this file upload.
Handling Buttons : Making Button Data Persist
Using Submit Buttons as HTML Buttons
There is still one popular HTML control that we haven’t covered-buttons. Often you
see buttons in web pages , they are more difficult to work with using server side
scripts for one reason – they pop back. That is there is no data that’s stored tat will be
sent to the server when a submit button is clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<script language= "JavaScript">
function setbutton1()
{
document.form1.button.value="button 1"
form1.submit()
}
function setbutton2()
{
document.form1.button.value="button 2"
form1.submit()
}
function setbutton3()
{
document.form1.button.value="button 3"
form1.submit()
}

</script>
</head>
<body>
<h1>handling buttons</h1>
<form name= "form1" method="post">
<input type="hidden" name="buttons">
<input type="button" value="button 1" onclick="setbutton1()">
<input type="button" value="button 2" onclick="setbutton2()">
<input type="button" value="button 3" onclick="setbutton3()">
</form>
<!-- You clicked -->
<?php
if(isset($_REQUEST["button"]))
{
echo $_REQUEST["button"],"<br>";
}

?>
</body>
</html>

Figure : Buttons in web pages

You might also like