Web Programming Using PHP
Unit 2 : Control Structures
PHP Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
• 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
• Nested if statement – if statement inside another if statement
• switch statement - selects one of many blocks of code to be executed
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax:
if(condition){
//code to be executed
} Flow chart
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if..else statements. So, we
can check multiple conditions using this statement.
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
<?php
$marks=69;
if ($marks<33){
echo "fail";
} else if ($marks>=34 && $marks<50) {
echo "D grade";
} else if ($marks>=50 && $marks<65) {
echo "C grade";
} else if ($marks>=65 && $marks<80) {
echo "B grade";
} else if ($marks>=80 && $marks<90) {
echo "A grade";
} else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
PHP nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works
like PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
1. The default is an optional statement. Even it is not important, that default must
always be the last statement.
2. There can be only one default in a switch statement. More than one default may lead
to a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch
expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and
less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
Example:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
PHP Loops
Loops are used to execute the same block of code again and again, as long as a certain
condition is true.
In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
<?php
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
?> output:12345
The break Statement
With the break statement we can stop the loop even if the condition is still true:
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
} Output: 12
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
} Output: 12456
The PHP do...while Loop
The do...while loop will always execute the block of code at least once, it will then check the
condition, and repeat the loop while the specified condition is true.
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6); output: 12345
The PHP for Loop
The for loop is used when you know how many times the script should run.
Syntax
for (expression1, expression2, expression3) {
// code block
}
for ($x = 0; $x < 10; $x++) {
echo ++$x ;
} output: 1357911
1. The first expression, $x = 0;, is evaluated once and sets a counter to 0.
2. The second expression, $x <= 10;, is evaluated before each iteration, and the code
block is only executed if this expression evaluates to true. In this example the
expression is true as long as $x is less than, or equal to, 10.
3. The third expression, $x++;, is evaluated after each iteration, and in this example, the
expression increases the value of $x by one at each iteration.
The foreach Loop on Arrays
The most common use of the foreach loop, is to loop through the items of an array.
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
?> output: red
green
blue
yellow
For every loop iteration, the value of the current array element is assigned to the
variable $x. The iteration continues until it reaches the last array element.
Associative arrays are different, associative arrays use named keys that you assign to them,
and when looping through associative arrays, you might want to keep the key as well as the
value.
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($members as $x => $y) {
echo "$x : $y <br>";
} output: Peter : 35
Ben : 37
Joe : 43
PHP Functions
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform a specific task
PHP User Defined Functions
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
Create a Function
A user-defined function declaration starts with the keyword function, followed by the name
of the function:
<!DOCTYPE html>
<html>
<body>
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
</body>
</html>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a
variable.
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
function familyName($fname) {
echo "$fname<br>";
}
familyName("Jane");
familyName("Ram");
familyName("Swamy");
familyName("Kalai"); output: Jane
Ram
Swamy
Kalai
PHP Functions - Returning values
To let a function return a value, use the return statement:
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
• PHP automatically associates a data type to the variable, depending on its value.
Since the data types are not set in a strict sense, you can do things like adding a string
to an integer without causing an error.
PHP exit() Function: In PHP, the exit() function prints a message and exits the application.
It’s often used to print a different message in the event of a mistake. Use exit() when there
is not an error and have to stop the execution.
Syntax:
exit("Message goes here");
or
exit();
Example:
<?php
$a = 10;
$b = 10.0;
if($a == $b) {
exit('variables are equal');
}
else {
exit('variables are not equal');
}
?>
Output: variables are equal
PHP die() Function:
In PHP, the die( ) function is used to immediately terminate script execution and output a
message. It is often used to handle critical errors or to provide custom error messages
before stopping the script execution abruptly.
Syntax
die(message);
Features
• The die() function halts the execution of the script immediately after its invocation.
• It is commonly used for error handling or to provide a custom message before
terminating script execution.
• If no message is provided, die() outputs a default message indicating "Died".
In PHP, die() is the same as exit(). A program’s result will be an empty screen. Use die()
when there is an error and have to stop the execution.
Syntax:
die("Message goes here");
or
die();
Example:
<?php
$num = 1;
// die can only print string values,
// hence there will be no output
die($num);
?> Output : No output
die() exit()
The die() method is used to throw
The exit() method is only used to exit the process.
an exception
The die() function is used to print The exit() method exits the script or it may be used to
the message. print alternate messages.
This method is from die() in Perl. This method is from exit() in C.
Passing variables with data between pages using URL
There are different ways by which values of variables can be passed between pages
State Management in PHP
HTTP is a stateless protocol which means every user request is processed independently and it has nothing to do
with the requests processed before it. Hence there is no way to store or send any user specific details using HTTP
protocol.
But in modern applications, user accounts are created and user specific information is shown to different users, for
which we need to have knowledge about who the user(or what he/she wants to see etc) is on every webpage.
PHP provides for two different techniques for state management of your web application, they are:
1. Server Side State Management
2. Client Side Server Management
Server Side State Management
In server side state management we store user specific information required to identify the user on the server. And
this information is available on every webpage.
In PHP we have Sessions for server side state management. PHP session variable is used to store user session
information like username, userid etc and the same can be retrieved by accessing the session variable on any
webpage of the web application until the session variable is destroyed.
Client Side State Management
In client side state management the user specific information is stored at the client side i.e. in the bowser. Again, this
information is available on all the webpages of the web application.
In PHP we have Cookies for client side state management. Cookies are saved in the browser with some data and
expiry date(till when the cookie is valid).
One drawback of using cookie for state management is the user can easily access the cookie stored in their browser
and can even delete it.
PHP Global Variables - Superglobals
Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of
scope - and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
Cookies:
• Cookie is a small piece of information stored as a file in the user's browser by the web
server. Once created, cookie is sent to the web server as header information with
every HTTP request.
• Cookies can contain 1KB (1024B) size of data.
How it works?
1. Server script sends a set of cookies to the browser For example name, age, or
identification number etc
2. Browser stores this information on local machine for future use
3. When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user
Uses of Cookies:
• To store information about visitors regarding the accessed website’s page.
• Number of visit and views.
• Store first visit information and update it in every visit that pointed towards better
experience of user.
Type of Cookies:
1. Session Cookie: This is a type of cookie that expires when the session will destroy.
2. Persistent Cookie: Persistent cookie is a kind of cookie that is stored permanently on
browser’s system and expires on some specific time.
Creation of Cookies: In PHP, we can create and set cookie by setcookie()
Syntax:
setcookie( name, value, expire, path, domain, secure );
Name: It is mandatory for the time of creation, other arguments are optional
Value: This sets the value of the named variable and is the content that you actually want to
store
Expiry: The expiry date in UNIX timestamp format. After this time cookie will become
inaccessible The default value is 0
Path: Specify the path on the server (website)for which the cookie will be available If set to
/, the cookie will be available within the entire domain
Domain: Specify the domain for which the cookie is available to eg [Link]
Security: This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP
name: It is mandatory for the time of creation, other arguments are optional.
secure: If it is set to 1, it means it is available and sent to PHP.
Example
setcookie ("username", Harsha ", time()+3600); // The setcookie () function must appear
BEFORE the <html>
In the above example, the Cookie name is username value is Harsha it expires in 1 hour It is
mentioned in seconds, 60 seconds multiplied by 60 minutes•
• To retrieve cookies data in PHP use $_COOKIES.
• To check if it is set or not, use isset() function
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + 3600, "/"); // 3600 = 1 hr
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Drawback of using cookies is it can easily retrieve and also easily deleted. It is not secure.
Delete Cookie. There are many other cookie functions like timezoneSet , …
•To delete a cookie, use the setcookie() function with an expiration date in the past
Example
<?
php
// set the expiration date to one hour ago
setcookie ("user", "", time()-3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Session:
• Session stores server-side information, so that all the information are accessible to all
the webpages.
• A session create an alternative way to make data accessible across the various pages of
an entire website is to use a PHP Session.
• A session is a file in a temporary directory on the server where registered session
variables and their values are stored.
• It is more secure than cookies.
• We know that HTTP is a stateless protocol so that previously performed task cannot
be remembered by current request.
For example, when we want to buy something online, we visit many e-commerce websites
and compare products. Some of them are added to cart for future reference. After few days
when we are ready to buy it, the information is still available as the cart session is set
earlier.
Session is size independent to store as many data the user wants.
Uses of Session:
1. It provides login and logout functionality to store and display relevant information.
2. PHP session technique is widely used in shopping websites where we need to store
and pass cart information e g username, product code, product name, product price
etc from one page to another
Creation of Session: In PHP, session starts from session_start() function and data can be set
and get by using global variables $_SESSION.
Example:
<?php
session_start();
$SESSION["username"] = "abc";
$SESSION["userid"] = "1";
?>
<html>
<body>
<?php
echo "Session variable is set";
?>
<button type="submit" href="[Link]"></button>
</body>
</html>
Destroy PHP session
To remove all global session variables and destroy the session, use session_unset() and
session_destroy()
<?php
session_start();
<!DOCTYPE html>
<body>
<php>
// remove all session variables
session_unset ();
// destroy the session variables
session_destroy();
echo "All session variables are now removed, and the session is destroyed."
?>
</body>
</html>