0% found this document useful (0 votes)
34 views125 pages

PHP Introduction

The document provides an introduction to PHP, a server-side scripting language used for web development, detailing its architecture, features, and applications. It explains web server operations, PHP's data types, variables, and constants, as well as the differences between echo and print statements. Additionally, it highlights PHP's ease of use, flexibility, and community support, making it a popular choice for backend development.

Uploaded by

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

PHP Introduction

The document provides an introduction to PHP, a server-side scripting language used for web development, detailing its architecture, features, and applications. It explains web server operations, PHP's data types, variables, and constants, as well as the differences between echo and print statements. Additionally, it highlights PHP's ease of use, flexibility, and community support, making it a popular choice for backend development.

Uploaded by

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

Topic: Introduction to PHP

Web Server Architecture


• Web server architecture refers to the structure and design of web servers,
outlining how they handle incoming requests and deliver web content.
There are two main approaches to web server architecture:
• Single-Tier (Single Server) Architecture:
In a single-tier architecture, a single server is responsible for both processing
requests and serving web content. This is suitable for small websites or
applications with low traffic. However, it has limitations in terms of
scalability and fault tolerance. If the server goes down, the entire service
becomes unavailable.
• Multi-Tier (Load-Balanced) Architecture:
In a multi-tier architecture, multiple servers are used to distribute the
workload and ensure high availability. This approach often involves load
balancers that evenly distribute incoming requests across a cluster of web
servers. Each server can serve web content independently, and if one
server fails, the load balancer redirects traffic to healthy servers, ensuring
uninterrupted service.
Working of Web Servers
A web server works in the following ways:
• Obtain the IP address from domain name: IP address is obtained in two
ways either by search in it in the cache or requesting DNS Servers
• Requests full URL from Browsers: After fetching IP address a full URL is
demanded from web server
• Web Server Responds to the request: In accordance with the request a
response is sent by the server in case of successful request otherwise
appropriate error message is sent
• The Web Page is displayed on the browser: After getting the response
from the server, the web browser displays the result
1.On the hardware side, a web server is defined as a computer that stores software
and another website raw data, such as HTML files, images, text documents, and
JavaScript files. The hardware of the web servers are connected to the web and
supports the data exchange with different devices connected to the Internet.
2.On the software side, a web server includes server software accessed through
website domain names. It controls how web users access the web files and ensures the
supply of website content to the end-user. The web server contains several
components, including an HTTP server.
Introduction
• PHP is a server side scripting language. that is used to
develop Static websites or Dynamic websites or Web
applications.
• PHP stands for Hypertext Pre-processor, that earlier stood for
Personal Home Pages.
php
Introduction
• PHP stands for Hypertext Preprocessor.
• PHP is an interpreted language, i.e., there is no need
for compilation.
• PHP is a server-side scripting language, which is used
to manage the dynamic content of the website.
• PHP can be embedded into HTML.
• PHP is an object-oriented language.
• PHP is an open-source scripting language.
• PHP is simple and easy to learn language.
Evaluation of PHP
• It is an open-source, interpreted, object-oriented server-side scripting
language that is used for web development

• Developed by the Rasmus Lerdorf in 1994


• The latest version of PHP is PHP versions 8 which is released on
November 24, 2022.

• It can be easily embedded with HTML files.


• HTML codes can also be written in a PHP file. The
PHP codes are executed on the server-side
whereas HTML codes are directly executed on the
browser
Why PHP?
• It is one of the widely used open-source general-purpose scripting language
that is used for backend Development

Easy to Learn: It is easier to learn for anyone who has come across to any programming
language for the first time.
Free of Cost: Since it is an open-source language, therefore developers are allowed to
use its components and all methods for free.
Flexible: Since It is a dynamically typed language, therefore there are no hard rules on
how to build features using it.
Supports nearly all databases: It supports all the widely used databases, including
MySQL, ODBC, SQLite etc.
Secured: It has multiple security levels provides us a secure platform for developing
websites as it has multiple security levels.
Huge Community Support: It is loved and used by a huge number of developers. The
developers share their knowledge with other people of the community that want to know
about it.
Applications of PHP
• Server-side web development: It is a development where the program runs on server
dealing with the generation of content of web page.
• Content management systems (CMS): It is a framework already designed by other
programmers and coders on which you can either contribute your knowledge and skills, or
just use those coders’ skills to design your own website or blog
• E-commerce websites: E-commerce, or electronic commerce, refers to the buying and
selling of goods and services over the internet.
• Database-driven applications: It is a software application that relies on a database to
store, manage, and retrieve data. It utilizes a database management system (DBMS) to
organize and manipulate data, enabling efficient data storage, retrieval, and management.
• Web APIs: It is an API as the name suggests, it can be accessed over the web using the
HTTP protocol. It is a framework that helps you to create and develop HTTP based
RESTFUL services.
echo
• echo is a statement, which is used to display the output.
• echo can be used with or without parentheses: echo(), and echo.
• echo does not return any value.
• We can pass multiple strings separated by a comma (,) in echo.
• echo is faster than the print statement.

?php <?php
echo "Hello by PHP echo"; echo "Hello by PHP echo
?> this is multi line
text printed by
PHP echo statement
Hello by PHP echo
";
?>

Hello by PHP echo this is multi line text printed by PHP echo statement
print
• print is a statement, used as an alternative to echo
<?php
at many times to display the output. $msg="Hello print() in PHP
• print can be used with or without parentheses. ";
• print always returns an integer value, which is 1. print "Message is: $msg";
• Using print, we cannot pass multiple arguments. Message is: Hello print() in
• print is slower than the echo statement. ?>
PHP
<?php <?php
print "Hello by PHP print "; print "Hello by PHP print
print ("Hello by PHP print()"); this is multi line
?> text printed by
PHP print statement
Hello by PHP print Hello by PHP
";
print() ?>

Hello by PHP print this is multi line text printed by PHP print statement
<?php
print "Hello escape \"sequence\" characters
by PHP print"; Hello escape "sequence" characters by PHP
?> print
Print Echo

Print statement does not Echo


support multiple arguments. statement supports multiple
Passing multiple arguments to it arguments. For example, echo
at a time will result in an error. "Hello", "World"; is valid.
For example: "Hello", "World";
will throw an error.
Print statement is slow as Echo statement is faster than a
compared to the echo print statement.
statement.
Print statement returns an Echo statement does
integer value that is set to 1. not return any value thus echo
statement has return type as
void.
Print statement behaves like a Echo statement does not
function. behave like a function.
Print statement is less Echo statement is more
preferable in comparison with preferred by developers as it is
the echo statement. faster than a print statement.
Print and echo
<?php
$name = "John";
$profile = "PHP Developer";
$age = 25;
echo $name , $profile , $age, " years <?php
old"; $name = "John";
?> $profile = "PHP Developer";
$age = 25;
JohnPHP Developer25 years old print $name , $profile , $age, "
years old";
?>

ERROR!
Parse error: syntax error,
unexpected token "," in
/tmp/7g8h5uTI86.php on line 5
Language Basics- Data Types

PHP data types are used to hold different types of data or values. PHP supports 8
primitive data types that can be categorized further in 3 types:
• Scalar Types (predefined)
• Compound Types (user-defined)
• Special Types
Language Basics- Data Types

PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

• boolean

• integer

• float

• string
Language Basics- Data Types

Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.

<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Language Basics- Data Types

Integer means numeric data with a negative or positive sign. It holds only whole numbers,
i.e., numbers without fractional part or decimal points.
Rules for integer:
• An integer can be either positive or negative.
• An integer must not contain decimal point.
• Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
• The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.

<?php
$dec1 = 34;
$oct1 = 0243;
Decimal number: 34
$hexa1 = 0x45; Octal number: 163
echo "Decimal number: " .$dec1. "</br>"; HexaDecimal
echo "Octal number: " .$oct1. "</br>"; number: 69
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Language Basics- Data Types

A floating-point number is a number with a decimal point. Unlike integer, it can


hold numbers with a fractional or decimal point, including a negative or positive
sign.
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

Addition of floating numbers: 73.812


Language Basics- Data Types
• A string is a non-numeric data type. It holds letters or any alphabets,
numbers, and even special characters.
• String values must be enclosed either within single quotes or in double
quotes. But both are treated differently. To clarify this, see the example
below:

<?php
$company = "Javatpoint";
//
both single and double quote statements will treat
different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Hello Javatpoint
Hello $company
Language Basics- Data Types

PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

• array
• object
Language Basics- Data Types
• An array is a compound data type. It can store multiple values of same data
type in a single variable.

<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>

array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3)
"KTM" } Array Element1: Royal Enfield Array Element2: Yamaha Array Element3:
KTM
Language Basics- Data Types
<html>
<body>

<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

</body>
</html>

array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }

The var_dump() function returns the data type and the value.
Language Basics- Data Types
• Objects are the instances of user-defined classes that can store both values
and functions. They must be explicitly declared.

<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>

Bike Model: Royal Enfield


Language Basics- Data Types

PHP Data Types: Special Types


There are 2 special data types in PHP.
• resource
The null type is PHP's unit type, i.e. it has only one value: null..
• NULL

• A resource is a special variable, holding a reference to an external resource. Resources are


created and used by special functions
• It refers the external resources like database connection, FTP connection, file pointers, etc.

<?php
$conn = ftp_connect("127.0.0.1") or die("Could not connect");
echo get_resource_type($conn);
?>
Language Basics- Data Types

NULL:
• A variable of type Null is a variable without any data. In PHP, null is not a value, and
we can consider it as a null variable based on 3 condition.
• If the variable is not set with any value.
• If the variable is set with a null value.
• If the value of the variable is unset.

<?php

$empty=null;
var_dump($empty);
?>
Language Basics- Data Types
<?php
$a1 = " ";
var_dump($a1);
echo "<br />";
$a2 = null;
var_dump($a2);
?>
PHP Variables
Next Top

• In PHP, a variable is declared using a $ sign followed by the variable name. Here,
some important points to know about variables:
• As PHP is a loosely typed language, so we do not need to declare the data types of
the variables. It automatically analyzes the values and makes conversions to its
correct datatype.
• After declaring a variable, it can be reused throughout the code.
• Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:


$variablename=value

PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.
PHP Variables
Rules for declaring PHP variable:
• A variable must start with a dollar ($) sign, followed by the variable name.
• It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
• A variable name must start with a letter or underscore (_) character.
• A PHP variable name cannot contain spaces.
• One thing to be kept in mind that the variable name cannot start with a
number or special symbols.
• PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.
PHP Variables
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>

string is: hello string


integer is: 200
float is: 44.6
PHP Variables
<html>
<?php
<body>
$x=5;
$y=6; <?php
$z=$x+$y; $x = 5.5;
echo $z; var_dump($x);
?> ?>

</body>
</html>

11
float(5.5)
PHP Constant
PHP constants are name or identifier that can't be changed during the
execution.
PHP constants can be defined by 2 ways:
• Using define() function define('PI', 3.14159);
• Using const keyword const AREA_UNIT = 'square units';

PHP constant: define()


• Use the define() function to create a constant. It defines constant at run time. Let's see
the syntax of define() function in PHP. define() is a function that takes
• define(name, value, case-insensitive)
a string as the constant name
• name: The name of the constant. and a value. It is defined outside
• value: The value to be stored in the constant. of classes or functions.
• case_insensitive: Defines whether a constant is case insensitive. By default this value is False, i.e.,
case sensitive.

<?php Sample Message


define("WELCOME", “Sample Message"); Sample Message
echo WELCOME, "\n";
define("HELLO", “Sample Message ", true);
echo hello;
?>
PHP Constant
constant() function: const is a language construct that is used inside classes and
interfaces. It is followed by the constant name and value, without the need for
parentheses.
.
Syntax
const CONSTANT_NAME = value;
const PI = 3.14;

<?php
const RGB = ['red', 'green', 'blue'];
echo RGB[2];
?>

blue
PHP Operators
• PHP Operator is a symbol i.e used to perform operations on operands.
• In simple words, operators are used to perform operations on variables or
values

• $num=10+20;//+ is the operator and 10,20 are operands

• Arithmetic operators Unary Operators: works on single


• Assignment operators operands such as ++, -- etc.
Binary Operators: works on two
• Comparison operators operands such as binary +, -, *, / etc.
• Increment/Decrement operators Ternary Operators: works on three
• Logical operators operands such as "?:".
• String operators
• Array operators
• Conditional assignment operators
PHP Operators
• The PHP arithmetic operators are used in conjunction with numeric values
to perform common arithmetic operations such as addition, subtraction,
multiplication, and so on.

Operator Name Example Output


+ Addition $x + $y Sum of $x and $y
- Subtraction $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 divided by $y

** Exponentiatio $x ** $y Result of raising $x to the $y'th


n power
PHP Operators
• arithmetic operators

<?php
$x = 10;
$y = 4;
echo($x + $y) . "\n";
echo($x - $y) . "\n";
echo($x * $y) . "\n";
echo($x / $y) . "\n";
echo($x % $y) . "\n";
echo($x ** $y) . "\n";
?> 14
6
40
2.5
2
10000
PHP Operators
• Assignment operators are used to assign values to variables.

Operator Name Example Output


= Assign $x = $y The left operand gets set to the value
of the expression on the right

+= Add and assign $x += $y Addition

-= Subtract and assign $x -= $y Subtraction

*= Multiply and assign $x *= $y Multiplication

/= Divide and assign $x /= $y Division


quotient
%= Divide and assign Modulus
modulus
PHP Operators
• Assignment operators
<?php
$x = 10;
echo $x . "\n";
$x = 20;
$x += 30;
echo $x . "\n";
$x = 50;
$x -= 20;
echo $x . "\n";
$x = 5;
$x *= 25;
echo $x . "\n";
$x = 50; 10
$x /= 10; 50
echo $x . "\n"; 30
$x = 100; 125
$x %= 15; 5
echo $x . "\n"; 10
?>
PHP Operators
• Comparison operators are used to compare two values in a Boolean
fashion.
Operator Name Example Output
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and
they are of the same type

!= Not equal $x != $y True if $x is not equal to $y

<> Not equal $x <> $y True if $x is not equal to $y

!== Not identical $x !== $y True if $x is not equal to $y, or


they are not of the same type

< Less than $x < $y True if $x is less than $y

> Greater than $x > $y True if $x is greater than $y

>= Greater than or equal to $x >= $y True if $x is greater than or


equal to $y
<= Less than or equal to $x <= $y True if $x is less than
PHP Operators
• Comparison operators.
<?php
$aFew = 4;
$some = "4"; The value on both sides
are same.
if($some == $aFew ){
echo "The value on both sides are same.";
}
?>

<?php
$aFew = 4.4;
$some = "4";
The value on both sides
if($some == $aFew ){ are not same.
echo "The value on both sides are same.";
}
else
{
echo "The value on both sides are not same.";
}
PHP Operators
• Comparison operators.
<?php
$a = 34;
$b = 34; not Equal
if('34' === 34){
echo "Equal";
}
else{
echo "not Equal";
}

<?php
$a = 42;
$b = 20; A is not less than B
if( $a < $b ) {
echo "A is less than B \n";
}else {
echo "A is not less than B \n";
}
?>
PHP Operators
• Increment operators are used to increment a variable's value while
decrement operators are used to decrement.

Operator Name Output


++$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, then decrements $x by one

<?php <?php
$x = 10;
$x = 10; echo $x++ . "\n";
echo ++$x . "\n"; echo $x . "\n";
echo $x . "\n"; ?>
?>

? ?
PHP Operators
• Logical operators are typically used to combine conditional statements.
Operator Name Example Output
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
! Not !$x true if $x is not true
PHP Operators
• Logical operators are typically used to combine conditional statements.

<?php
$year = 2021;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>

2021 is not a leap year.


PHP Operators
• Logical operators are typically used to combine conditional statements.

a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("The numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
print("The numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")

Hello World!
Hello World!
PHP Operators
String Operators are specifically designed for strings.

Operator Name Example Output


. Concatenation $str1 . $str2 Concatenation
of $str1 and $str2
.= Concatenation $str1 .= $str2 Appends the $str2 to
assignment the $str1

<?php

$x = "Hello";
$y = " World!";
echo $x . $y . "\n";

$x .= $y;
echo $x . "\n";
?>

The numbers are greater than 0


Atleast one number is not greater than 0
PHP Operators
Array operators are used to compare arrays.
Operator Name Example Output
+ Union $x + $y Union of $x and $y

== Equality $x == $y True if $x and $y have the same


key/value pairs

=== Identity $x === $y True if $x and $y have the same


key/value pairs in the same order and
of the same types

!= Inequality $x != $y True if $x is not equal to $y

<> Inequality $x <> $y True if $x is not equal to $y

!== Non-identity $x !== $y True


PHP Operators
Array operators are used to compare arrays.

<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue"); array(6) {
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink"); ["a"]=>
$f= $x; string(3) "Red"
$z = $x + $y; ["b"]=>
var_dump($z); string(5) "Green"
echo "\n";
["c"]=>
var_dump($x == $y);
var_dump($x == $f); string(4) "Blue"
?> ["u"]=>
string(6) "Yellow"
["v"]=>
string(6) "Orange"
["w"]=>
string(4) "Pink"
}
bool(false)
bool(true)
PHP Operators
Conditional assignment operators are used to set a value depending on
conditions.
Operator Name Example Output
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x. The value of $x is
expr2 if expr1 = true. The value of $x is expr3 if
expr1 = false

$var = (condition)? value1 : value2;

<?php
$a = 10;
$b = 20;
$result = ($a > $b ) ? $a :$b;
Greater Value is 20
echo "Greater Value is $result\n";

?>
PHP 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
Array Items
• Array items can be of any data type.
• The most common are strings and numbers (int, float), but array items
can also be objects, functions or even arrays.
• You can have different data types in the same array.
• Array Functions
• The real strength of PHP arrays are the built-in array functions, like the
count() function for counting array items:
• PHP Indexed Arrays
• In indexed arrays each item has an index number.
• By default, the first item has index 0, the second item has item 1, etc.
• Loop through Indexed array
• PHP Associative Arrays
• Associative arrays are arrays that use named keys that you assign to
them.
Access Associative Arrays
To access an array item you can refer to the key name.
• Add Array Item
• To add items to an existing array, you can use the bracket [] syntax.
• Add Multiple Array Items
• To add multiple items to an existing array, use the array_push() function.
• Remove Array Item
• To remove an existing item from an array, you can use the array_splice()
function.
• With the array_splice() function you specify the index (where to start) and
how many items you want to delete.
• Remove Item From an Associative Array
• To remove items from an associative array, you can use the unset()
function.
• Specify the key of the item you want to delete.
• 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.
• 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:


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:
Decision Making in PHP
• Any PHP script is built out of a series of statements. A
statement can be an assignment, a function call, a
loop, a conditional statement of even a statement that
does nothing (an empty statement).
• Statements usually end with a semicolon. In addition,
statements can be grouped into a statement-group by
encapsulating a group of statements with curly
braces.
• If the condition is true, the conditional statements
will be run. However, if the condition is false, other
statements will sometimes be run instead.
Decision Making in PHP
PHP programming enables the application of decision-making by the
following conditional statements:
• if Statement
• if … else Statement
• elseif Statement
• switch Statement

PHP enables actions to be performed based on logical and comparative conditions.


In addition, the result of these circumstances (either TRUE or FALSE) will be a user-
requested action.
Decision Making in PHP
• if Statement: The PHP if statement is the simplest form of conditional
statement when applied to a program. A piece of code is only executed if the
condition evaluates to true.
• In addition, the if statement allows programmers to determine an action
depending on a particular condition.

Syntax:
if (condition){
// execute this block if true }

<?php $num = 25;


if ($num > 10)
{ echo "$num is greater than 10."; } ?>

25 is greater than 10.


Decision Making in PHP
• if … else decision-making in PHP allows programmers to have two
executable blocks of code to support either true or false results

Syntax:
if (condition) {
// execute this block if the result is true
}
else{
// execute this block if the result in the first block is
false
}

<?php $num = 25;


if ($num > 100)
{ echo "$num is greater than 100."; } else
{ echo "$num is less than 100."; }
?> 25 is less than 100.
Decision Making in PHP
• Another condition in PHP is the elseif statement, which enables programmers to
include multiple conditions within the if… else statements.
• As a clarification, you can use the else statement (after an if) to describe a block of
code that will only be executed if the first condition is fals

<?php
if (condition) {
// execute this block if the result is true $a=10;
}
$b=20;
elseif {
// execute this block if the result in the first block is false if ($a > $b) {
}
echo "a is bigger than b";
else {
// execute this block if the result in the first and second blocks are } elseif ($a == $b) {
false
echo "a is equal to b";
}
} else {
echo "a is smaller than b";
25 is less than 100.
}
?>
Decision Making in PHP
elseif statement
Decision Making in PHP
<?php
$a=10;
$b=20;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

a is smaller than b
Decision Making in PHP
• The switch statement executes several cases that match the
condition and executes the case block as appropriate.
• It evaluates an expression before comparing it with each case’s
values. As a result, whenever a case is matched, an identical case is
run.
• However, to use the switch statement in PHP decision-making, you
have to be familiar with two distinct terms:
 break – After the code for the first true case has been run, it tells the
program to leave the switch-case statement block.
 default – It is applied when there is no case in which the constant-
expression value equals the expression’s value. If there is no default
statement and there is no case match, none of the statements in the
switch body are run.
Decision Making in PHP
switch ( expression ) { <?php
case result1: $i=10;
// execute this if expression results in result1 switch ($i) {
break; case 0:
case result2: echo "i equals 0";
// execute this if expression results in result2 break;
break; case 1:
default: echo "i equals 1";
// execute this if no break statement break;
// has been encountered hitherto case 2:
} echo "i equals 2";
break;
default:
echo "i is greater than 3";
i is greater than 3 }
?>
Decision Making in PHP
Decision Making in PHP
<?php case "Fri":
$d = date("D"); echo "Today is Friday";
break;
switch ($d){
case "Mon": case "Sat":
echo "Today is Monday"; echo "Today is Saturday";
break; break;

case "Tue": case "Sun":


echo "Today is Tuesday"; echo "Today is Sunday";
break; break;

case "Wed": default:


echo "Today is Wednesday"; echo "Wonder which day is this ?";
break; }
?>
case "Thu":
echo "Today is Thursday";
break; Today is Tuesday
Looping Statement in PHP
• PHP for loop can be used to traverse set of code for the specified number of times.
• It should be used if the number of iterations is known otherwise use while loop. This
means for loop is used when you already know how many times you want to execute a
block of code.

• while — loops through a block of code as long as the condition specified


evaluates to true.
• do…while — the block of code executed once and then condition is
evaluated. If the condition is true the statement is repeated as long as the
specified condition is true.
• for — loops through a block of code until the counter reaches a specified
number.
• foreach — loops through a block of code for each element in an array.
Looping Statement in PHP
• The while loop is also called an Entry control loop because the condition is checked
before entering the loop body. This means that first the condition is checked. If the
condition is true, the block of code will be executed.

while(condition){
//code to be executed
}
Looping Statement in PHP
<?php
1
$n=1;
2
while($n<=10){
3
echo "$n<br/>";
4
$n++;
5
}
6
?>
7

<?php 8
$n=1; 9
while($n<=10):
echo "$n<br/>"; 10
$n++;
endwhile;
?>
Looping Statement in PHP
• The do-while loop is also called an Exit control loop. The do-while loop is a variant of
while loop, which evaluates the condition at the end of each loop iteration. With a do-
while loop the block of code executed once, and then the condition is evaluated, if the
condition is true, the statement is repeated as long as the specified condition evaluated
to is true.

do{
// Code to be executed
}
while(condition);
Looping Statement in PHP
<?php
$i = 1;
The number is 2
do{
The number is 3
$i++; The number is 4
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
Looping Statement in PHP
• The for loop repeats a block of code as long as a certain condition is met. It is typically
used to execute a block of code for certain number of times.
Entry control loop

<?php

for (initialize; condition; increment)

{ //code to be executed }

?>
Looping Statement in PHP
The parameters of for loop have following meanings:
• initialization — it is used to initialize the counter variables, and evaluated once
unconditionally before the first execution of the body of the loop.
• condition — in the beginning of each iteration, condition is evaluated. If it evaluates
to true, the loop continues and the nested statements are executed. If it evaluates
to false, the execution of the loop ends.
• increment — it updates the loop counter with a new value. It is evaluate at the end of
each iteration.

<?php
The number is 1
for($i=1; $i<=3; $i++) The number is 2
The number is 3
{ echo "The number is " . $i . “\n"; }

?>
Looping Statement in PHP
The foreach loop is used to iterate over arrays.

foreach($array as $value){
// Code to be executed
}

<?php
$colors = array("Red", "Green", "Blue");
// Loop through colors array
foreach($colors as $value){
Red
echo $value . “\n"; Green
} Blue
?>
Looping Statement in PHP

<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "[email protected]",
"age" => 18
);
// Loop through superhero array
foreach($superhero as $key => $value){ name : Peter Parker
email :
echo $key . " : " . $value . "\n>";
[email protected]
} age : 18
Include and Require
• It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with
the include or require statement.

• The include and require statements are identical, except upon failure:

• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue

• So, if you want the execution to go on and show users the output, even if the include file is missing, use the
include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use
the require statement to include a key file to the flow of execution. This will help avoid compromising your
application's security and integrity, just in-case one key file is accidentally missing.

• Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for
all your web pages. Then, when the header needs to be updated, you can only update the header include
file.
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:

Output
Output
• PHP include vs. require

• The require statement is also used to include a file into the PHP code.

• However, there is one big difference between include and require; when a
file is included with the include statement and PHP cannot find it, the
script will continue to execute:

Output
• If we do the same example using the require statement, the echo
statement will not be executed because the script execution dies after
the require statement returned a fatal error:

Output
Capturing Form Data
Capturing Form Data
• There exist two methods in PHP to collect data submitted in a FORM.

• PHP GET Method and PHP POST Method.

• In the PHP POST method, data from HTML FORM is submitted/collected using a
super global variable $_POST.

• This method sends the encoded information embedded in the body of the HTTP
request and hence the data is not visible in the page URL unlike the GET Method.

• HTTP protocol enables the communication between the client and the server
where a browser can be the client, and an application running on a computer
system that hosts your website can be the server.
Capturing Form Data
• The GET method is used to submit the HTML form data. This data is
collected by the predefined $_GET variable for processing.
• The information sent from an HTML form using the GET method is visible to
everyone in the browser's address bar, which means that all the variable
names and their values will be displayed in the URL. Therefore, the get
method is not secured to send sensitive information.

For Example
localhost/gettest.php?username=Harry&bloodgroup=AB+
Get method in PHP
<html> Index.html
<body>

<form action = "gettest.php" method = "GET">


Username: <input type = "text" name = "username" /> <br>
Blood Group: <input type = "text" name = "bloodgroup" /> <br>
<input type = "submit" /> gettest.php
</form> <html>
<body>
</body>
</html> Welcome <?php echo $_GET["username"]; ?> </br>
Your blood group is: <?
php echo $_GET["bloodgroup"]; ?>

When the user will click </body>


on Submit button after filling the </html>
form, the URL sent to the server
could look something like this: The output will look like the below
localhost/gettest.php? output:
username=Harry&bloodgroup=AB Welcome Harry Your blood group is: AB-

-
Get method in PHP
Advantages of GET method (method = "get")
• You can bookmark the page with the specific query string because the data
sent by the GET method is displayed in URL.
• GET requests can be cached.
• GET requests are always remained in the browser history.

Disadvantages of GET Method


• The GET method should not be used while sending any sensitive
information.
• A limited amount of data can be sent using method = "get". This limit
should not exceed 2048 characters.
• For security reasons, never use the GET method to send highly sensitive
information like username and password, because it shows them in the
URL.
• The GET method cannot be used to send binary data (such as images or
word documents) to the server.
Get method in PHP
<html>
Index.html
<body>
<form action="getmethod.php" method="GET">
Username:
<input type="text" name="username" /> <br>
City:
<input type="text" name="city" /> <br>
<input type="submit" /> getmethod.p
</form> <html>
</body>
hp
<body>
</html> Welcome
<?php echo $_GET["username"]; ?> </br>
Your City is:
<?php echo $_GET["city"]; ?>
</body>

</html>
Post method in PHP
• POST method is also used to submit the HTML form data. But the data
submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.
• Unlike the GET method, it does not have a limit on the amount of
information to be sent. The information sent from an HTML form using the
POST method is not visible to anyone.

For Example
localhost/posttest.php
Post method in PHP
Advantages of POST method (method =

"post"):

• The POST method is useful for sending any

sensitive information because the

information sent using the POST method is


Disadvantages of POST Method
• POST requests do not cache.
• not
POSTvisible to remain
requests never anyone.
in the browser history.
• It is not possible to bookmark the page because the variables are not
displayed in URL.
• There is no limitation on size of data to be
Post method in PHP
<html>
Index.html
<body>
<form action = "posttest.php" method = "post">
Username: <input type = "text" name = "username" /
> <br>
Blood Group: <input type = "text" name = "bloodgroup" /
> <br>
<input type = "submit" /> posttest.php
</form> <html>
<body>
</body>
</html> Welcome <?php echo $_POST["username"]; ?> </
br>
Your blood group is: <?
Welcome Harry Your blood group is: php echo $_POST["bloodgroup"]; ?>
O+
</body>
</html>
Dealing with Multi-value filed
Index.php
<html>
<body> </body>
<!--name.php to be called on form submission--> </html>
<form method = 'post'> <?php
<h4>SELECT SUBJECTS</h4> // Check if form is submitted successfully
<select name = 'subject[]' multiple size = 6> if(isset($_POST["submit"]))
<option value = 'english'>ENGLISH</option> {
<option value = 'maths'>MATHS</option> posttest.php
// Check if any option is selected
<option value = 'computer'>COMPUTER</option> if(isset($_POST["subject"]))
<option value = 'physics'>PHYSICS</option> {
<option value = 'chemistry'>CHEMISTRY</option> // Retrieving each selected option
<option value = 'hindi'>HINDI</option> foreach ($_POST['subject'] as
</select> $subject)
<input type = 'submit' name = 'submit' value = Submit> print "You selected $subject<br/>";
</form> }
else
echo "Select an option first !!";
}
?>
What is a Cookie?
• A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With PHP,
you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.

• setcookie(name, value, expire, path, domain, secure, httponly);


PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John
Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that
the cookie is available in entire website (otherwise, select the directory you
prefer).
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:
• Modify a Cookie Value
• To modify a cookie, just set (again) the cookie using the setcookie()
function:
Delete a Cookie
To delete a cookie, use the setcookie() function with
an expiration date in the past:
Check if Cookies are Enabled
The following example creates a small script that checks whether
cookies are enabled. First, try to create a test cookie with the
setcookie() function, then count the $_COOKIE array variable:
Session
• A session is a way to store information (in variables) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the users computer.
What is a PHP Session?
• When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session. The computer knows who you are. It knows when
you start the application and when you end. But on the internet there is one
problem: the web server does not know who you are or what you do, because the
HTTP address doesn't maintain state.
• Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc).
• So; Session variables hold information about one single user, and are available to all
pages in one application.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page,
we start a new PHP session and set some session variables:
Get PHP Session Variable Values
Next, we create another page called "demo_session2.php". From this page, we will
access the session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they
are retrieved from the session we open at the beginning of each page
(session_start()).
Also notice that all session variable values are stored in the global $_SESSION
variable:
Destroy a PHP Session
To remove all global session variables and destroy the session, use
session_unset() and session_destroy():
PHP File Handling

File handling is an important part of any web application. You often need to
open and process a file for different tasks.
PHP readfile() Function

The readfile() function reads a file and writes it to the output buffer.
PHP Open File - fopen()
A better method to open files is with the fopen()
function. This function gives you more options than the
readfile() function.
• PHP Create File - fopen()
• The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a
file is created using the same function used to open files.
• If you use fopen() on a file that does not exist, it will create it, given that the file is
opened for writing (w) or appending (a).
• The example below creates a new file called "testfile.txt". The file will be created in the
same directory where the PHP code resides.
• PHP Write to File - fwrite()
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
• The example below writes a couple of names into a new file called "newfile.txt":
• PHP Append Text
• You can append data to a file by using the "a" mode. The "a" mode
appends text to the end of the file, while the "w" mode overrides (and
erases) the old content of the file.
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open
file!");
$txt = “MIT WPU\n";
fwrite($myfile, $txt);
$txt = “FYMCA\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
fruits.csv

Reading a CSV file and display the content in browser


Ajax

113
Synchronous web communication

• synchronous: user must wait while new pages load


• the typical communication pattern used in web pages
(click, wait, refresh)

114
Web applications and Ajax
• web application: a dynamic web site that mimics the feel of a desktop
app
• presents a continuous user experience rather than disjoint pages
• examples: Gmail, Google Maps, Google Docs and Spreadsheets, Flickr, A9

115
Web applications and Ajax
• Ajax: Asynchronous JavaScript and XML
• not a programming language; a particular way of using JavaScript
• downloads data from a server in the background
• allows dynamically updating a page without making the user wait
• avoids the "click-wait-refresh" pattern
• Example: Google Suggest

116
Asynchronous web communication

• asynchronous: user can keep interacting with page


while data loads
• communication pattern made possible by Ajax

CS380 117
XMLHttpRequest

• JavaScript includes an XMLHttpRequest object that can fetch files


from a web server
• supported in IE5+, Safari, Firefox, Opera, Chrome, etc. (with minor
compatibilities)
• it can do this asynchronously (in the background, transparent to user)
• the contents of the fetched file can be put into current web page
using the DOM

118
A typical Ajax request
1. user clicks, invoking an event handler
2. handler's code creates an XMLHttpRequest object
3. XMLHttpRequest object requests page from server
4. server retrieves appropriate data, sends it back
5. XMLHttpRequest fires an event when data arrives
• this is often called a callback
• you can attach a handler function to this event
6. your callback event handler processes the data and
displays it

119
A typical Ajax request

120
Output

122
Prototype Ajax methods and
properties
event description
onSuccess request completed successfully
onFailure request was unsuccessful
request has a syntax error,
onException security error, etc.

events in the Ajax.Request object that you can handle

123
Basic Prototype Ajax template
property description
the request's HTTP error code
status (200 = OK, etc.)
statusText HTTP error code text
the entire text of the fetched
responseText page, as a String
the entire contents of the
responseXML fetched page, as an XML DOM
tree

function handleRequest(ajax) {
alert(ajax.responseText);
} JS
124
125

You might also like