Chapter 5.2 PHP
Chapter 5.2 PHP
Internet Programming
9/7/2020
XAMPP Server Installation
• Check httpd.conf file for
• DocumentRoot – The directory in which client requests are placed, to
be processed on Apache web server.
• DocumentRoot “C:/xampp/htdocs"
9/7/2020
PHP
•PHP Syntax
<?php
//php code
?>
9/7/2020
PHP
• PHP: Embedded in HTML
<html>
<head>
<title>Listing 1</title>
<body> Today’s date is <?php echo ("d/m/Y");?>
</body>
</html>
9/7/2020
PHP: Variables
•Variables are containers for storing data.
•Rules for PHP variables:
• A variable starts with a $ sign , followed by the name of the
variable
• A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores
• Variable names are case-sensitive
9/7/2020
PHP: Datatypes
• PHP includes the following 8 data types:
• Integer- Represent a whole number wth no fractional component.
• Floating point numbers - Repesent real numbers that include decimal place.
• String- Represent text literals of arbitrary length.
• Boolean- Represent a true or false value.
• Array- Represents a variable that stores a collection of related data elements.
• Object- Allows you to store data as well as information for its processing.
• Resource- Refers to a special data type that is used to store references to external
functions and resources of PHP.
• Null- Refers to a special data type that holds a single value, i.e. null.
9/7/2020
PHP: Variables and Data types example
<?php
$a=5;
$b=4.5;
$c="PHP tutorial";
$d=true;
$e=null;
echo(gettype($a))."<br>";
echo(gettype($b))."<br>";
echo(gettype($c))."<br>";
echo(gettype($d))."<br>";
echo(gettype($e))."<br>";
unset($a); //destroy variable
echo gettype($a);
?>
9/7/2020
PHP: List of specialized functions
Functions Purpose
is_bool() Tests if a variable holds a boolean value.
is_numeric() Tests if a variable holds a numeric value.
is_int() Tests if a variable holds an integer.
is_float() Tests if a variable holds a folating-point value.
is_string() Tests if a variable holds a string value.
is_null() Tests if a variable holds a NULL value.
is_array() Tests if a variable is an array.
is_object() Tests if a variable is an object.
9/7/2020
PHP: Datatypes and Typecasting
<?php
$a=5;
$b=4.5;
$c="PHP tutorial";
$d=true;
$e=null;
echo(is_int($a))."<br>";
echo(is_float($b))."<br>";
echo(is_string($c))."<br>";
echo(is_bool($d))."<br>";
echo(is_null($e))."<br>";
$a=(float)$a;
echo(gettype($a))."<br>";
settype($b,"int");and
echo(gettype($b));
?>
9/7/2020
PHP: Operators
<?php
$txt="Learning PHP"
$x=5;
$y=2;
echo $x+$y."<br>";
echo $x-$y."<br>";
echo $x*$y."<br>";
echo $x/$y."<br>";
echo $x**$y."<br>";
echo $x."%".$y."=".($x%$y)."<br>";
$x++;
echo $x."<br>";
$y--;
echo $y;
?>
9/7/2020
Control Structures
• Conditional Statements
• The if Statement
• The if-else Statement
• The if-else-if Statement
• The switch Statement
• The Nested if-else Statements
• Looping Statements
• The while loop
• The do-while loop
• The for loop
• The foreach loop
• Break, Continue and Exit statements
• Break
• Continue
9/7/2020
Conditional Statement: if
<?php
$x=1;
if($x==1)
print ‘$x is equal to $1’;
?>
9/7/2020
Conditional Statement:if-else
<?php
$a=34;
$b=45;
if($a > $b)
{
echo “a is greater than b”;
}
else
{
echo “a is not greater than b”;
}
?>
9/7/2020
Conditional Statement:if-elseif-else
<?php
$a=7;
$b=9;
$c=5;
if($a > $b && $a > $c)
{ echo "largest number is ".$a;}
elseif ($b > $a && $b > $c)
{ echo "largest number is ".$b;}
else
{echo "largest number is ".$c;}
?>
9/7/2020
Conditional Statement:if - elseif-else example 2
<?php
echo date("Y/m/d")."<br>";
$d = date("D");
echo $d."<br>";
if($d == "Fri")
{echo "Have a nice weekend!";}
elseif($d == "Sun")
{echo "Have a nice Sunday!";}
else
{echo "Have a nice day!";}
?>
9/7/2020
Conditional Statement:Switch..case
input.html file Your Choice :
<!DOCTYPE html> <input type="radio"
<html> name="choice" value="1" />Largest Digit
<body> <input type="radio"
name="choice" value="2" />Sum of Digits
<h1>Three services are available</h1>
<input type="radio"
<fieldset> name="choice" value="3" />Reverse of a
<legend>Give number and choose number
service</legend> <br/> <br/>
<input type="submit"
<form action="output.php" value="Submit">
method="post"> </form>
Give an integer > 0 : </fieldset>
<input type="text" </body>
name="num"><br/><br/>
</html>
9/7/2020
Conditional Statement:Switch..case
output.php file
<html>
<body>
<?php
$n=$_REQUEST['num'];
$ch=$_REQUEST['choice'];
switch($ch)
{
case 1:$max=0;
do{
$last_digit=$n%10;
if($last_digit > $max)
$max=$last_digit;
9/7/2020
$n=floor($n/10);
Conditional Statement:Switch..case
while($n>0);
print("<h1>Largest digit is:".$max."</h1>");
break;
case 2:$sum=0;
do{
$last_digit=$n%10;
$sum+=$last_digit;
$n=(integer)($n/10);
}
while($n>0);
print("<h1>Sum of digits is:".$sum."</h1>");
break;
9/7/2020
Conditional Statement:Switch..case
case 3:$n_rev=0;
do{
$last_digit=$n%10;
$n_rev=$n_rev*10+$last_digit;
$n=(integer)($n/10);
}
while($n>0);
print("<h1>Reverse number is:".$n_rev."</h1>");
break;
default:print("<h1>Error</h1>");
break;
}
?>
</body>
</html>
9/7/2020
Conditional Statement:Nested if-else stattement
<?php
$num=15;
if($num<=0)
{
if($num===0)
{ echo “You have entered zero”; }
else
{ echo $num. “ is a negative number”; }
}
else
echo $num. “ is a positive number”;
?>
9/7/2020
PHP
• PHP: Function
<?php
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);
?>
9/7/2020
PHP
• PHP: Arrays
<?php
$a = array("text", "HTML", "CSS", "JavaScript", "PHP");
echo "PHP files can contain " . $a[0] . ", " . $a[1] . ", " . $a[2] . ", " .$a[3] . " and " . $a[4];
?>
9/7/2020
Looping statement: for
factorial_1.html file </script>
<!DOCTYPE html> </head>
<html> <body>
<head> <form name="form1"
<title> Calculate factorial of a number</title> action="factorial_2.php" onsubmit="return
<script> validateForm()" method="get">
function validateForm() { Name: <input type="text" name="num">
var x = <input type="submit" value="Submit">
document.forms["form1"]["num"].value; </form>
if (x == "") {
alert("Enter a number");
return false;
}
}
9/7/2020
Looping statement: for
• factorial_2.php file
<?php
$f_num=$_GET['num'];
$factorial=1;
for($x=$f_num; $x>=1; $x--)
{
$factorial=$factorial * $x;
}
echo "Factorial of $f_num is $factorial";
?>
9/7/2020
Looping statement: foreach
<?php
$email=array(‘Saurabh Gupta’,’Sulabh Dixit’);
foreach ($email as $value)
{
echo “Processing “.$value.”<br />”;
}
?>
9/7/2020
Looping statement: while
fact_1.html file </script>
<!DOCTYPE html> </head>
<html> <body>
<head> <form name="form1" action="fact_2.php"
<title> Calculate factorial of a onsubmit="return validateForm()"
number</title> method="get">
<script> Name: <input type="text" name="num">
function validateForm() { <input type="submit" value="Submit">
var x =
document.forms["form1"]["num"].value; </form>
if (x == "") { </body>
alert("Enter a number"); </html>
return false;
}
}
9/7/2020
Looping statement: while
• fact_2.php file
<?php
$f_num=$_GET['num'];
$factorial=1;
$x=$f_num;
while($x>=1)
{
$factorial=$factorial * $x;
$x--;
}
echo "Factorial of $f_num is $factorial";
?>
9/7/2020
Looping statement: do..while
fact_1.html file </script>
<!DOCTYPE html> </head>
<html> <body>
<head> <form name="form1" action="fact_2.php"
<title> Calculate factorial of a onsubmit="return validateForm()"
number</title> method="get">
<script> Name: <input type="text" name="num">
function validateForm() { <input type="submit" value="Submit">
var x = </form>
document.forms["form1"]["num"].value; </body>
if (x == "") { </html>
alert("Enter a number");
return false;
}
}
9/7/2020
Looping statement: do..while
• fact_2.php file
<?php
$f_num=$_GET['num'];
$factorial=1;
$x=$f_num;
do
{
$factorial=$factorial * $x;
$x--;
}while($x>=1);
echo "Factorial of $f_num is $factorial";
?>
9/7/2020
Break statement
• The break statement when enters in a loop skips the remaining statements in the loop
body and breaks the loop.
<?php
for($i=0;$i<=10;$i++)
{
if($i==3)
{
break;
}
echo “The number is”.$i;
echo “<br/>”;
}
echo “This is a break statement”;
?>
9/7/2020
Continue statement
•The continue statement passes the control to the current iteration, skipping all remaining
statements in the loop. It returns to the top of the loop and allows it to continue running.
<?php
for($i=0;$i<5;++$i)
{
if($i==2)
{
continue;
}
echo “The number is”.$i;
echo “<br/>”;
}
?>
9/7/2020
Exit statement
•The exit statement is used when you want to stop a program from running. It can block
infinite looping statements in the program.
<?php
for($i=0;$i<5;++$i)
{
if($i==2)
{
exit;
}
echo “The number is”.$i;
echo “<br/>”;
}
echo “This is exit statement”;
?>
9/7/2020
Built-in Functions in PHP
• String Manipulation Functions
• Date and Time Functions
• Mathematical Functions
9/7/2020
String Manipulation Functions
• The strlen() function returns the length of a string.
•Syntax : strlen(string $string)
<?php
$string="Internet Programming";
echo "The length of a string is:".strlen($string);?> // Output : 20
• The strpos() function is used to find the position of the first occurance of a string
in another string (case-sensitive). It returns the position of the string in integer
format.
•Syntax: int strpos($string, find, start)
<?php
$string="Welcome to PHP Tutorial";
echo "The position of PHP is:".strpos($string,"PHP"); ?> //Output : 11
9/7/2020
String Manipulation Functions
• The str_repeat() function is used to repeat a string for a specific number of times.
•Syntax : string str_repeat(string $string, repeat)
<?php
$string="PHP";
echo "The repeated string is:".str_repeat($string, 3);?>
• The strrev() function reverses a string. The return value of the function is the
reversed string.
•Syntax: int strrev(string $string)
<?php
$string=”Programming”;
echo “The reversed string is:”.strrev($string); ?>
9/7/2020
Date and Time Functions
• The date() function is used to format the local time and date. It returns the
formatted date and time values.
•Syntax: date(format, timestamp)
•Some of the characters that can be used with the date format are as follows:
9/7/2020
Date and Time Functions
Character Purpose
d Specifies the day of the month (from 01 to 31)
D Specifies a textual representation of a day (three letters)
F Specifies a full textual representation of a month(January through December)
t Specifies the number of days in the given month
g Specifies 12-hour format of an hour(1 to 12)
L Specifies whether it’s a leap year (1 if it is a leap year, 0 otherwise)
l Specifies the full textual representation of a day
h Specifies 12-hour format of an hour (01 to 12)
i Specifies minutes with leading zeros (00 to 59)
s Specifies seconds with leading zeros (00 to 59)
Y Specifies a four-digit representation of a year
a Specifies a lowercase am or pm
S Specifies the English ordinal suffix for the day of the month(st, nd, rd, or th)
9/7/2020
Date and Time Functions
<?php
echo date("l")."<br/>";
echo (date("l dS \of F Y h: i: s a")."");
?>
Output:
Saturday
Saturday 21st of August 2021 07: 04: 17 pm
9/7/2020
Mathematical Functions
• The rand() function is used to generate a random integer.
• Syntax: int rand (void)
• Syntax: int rand (int $min, int $max)
<?php
echo(rand()."<br/>");
echo(rand()."<br/>");
echo(rand(40,80));
?>
• The log() function returns the natural logarithm.
• Syntax: log(number, base)
9/7/2020
Mathematical Functions
<?php
echo(log(2.575)."<br/>");
echo(log(2)."<br/>");
echo(log(1)."<br/>");
echo(log(0)."<br/>");
?>
9/7/2020
Tracking users - Cookie
• Cookies are the small files that contain information about the user’s
computer that are embedded by the server.
• Each time the same computer requests a webpage from a browser, it sends
the cookie with the requested web page.
• In PHP, you can create and retrieve cookie values.
• The size of the cookie should not exceed 1K (1024 bytes).
• One common use of cookies is that it stores your username and password
on your computer so that you do not need to enter your credentials each
time you visit a website.
• Attributes of a cookie
• Name value - Represents the variable name and corresponding value to be
stored in the cookie.
• Expiration date - Determines the time when to delete a cookie.
• Valid domain - Represents a domain name (partial or complete) to which
the cookie is sent.
9/7/2020
Tracking users - Cookie
• Valid Path - Identifies sites within various paths in the same domain.
• Security Flag - Constrains a browser from transferring cookie data over
unsecured connections. It allows the cookie to be sent over any type of HTTP
connection.
•Example:
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "PHP developer's Team";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
9/7/2020
Tracking users - Cookie
<?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];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the
cookie.</p>
</body>
</html>
9/7/2020
Tracking users - Session
• A session is used to store information that is used across multiple web pages.
• It stores different information for each user accessing a website.
• A session includes server-side and client-side cookies, where the client-side cookie
contains a reference to the requested data on the server.
• When a user visits a website, the Web browser sends the reference code to the
server, which loads the requested data.
• A file is created by the session within a temporary directory on the server.
• In this file, the registered session variables and their values are stored.
• The session information is lost when the user exits the website.
• Starting a session - In PHP, Sessions are called using the session_start() function.
• An associative array, namely $_SESSION[] stores the session variable.
9/7/2020
Tracking users - Session
• Creating a session <html>
<?php <head>
session_start(); <title>Setting up a PHP session</title>
if(isset($_SESSION['counter'])) </head>
{ $_SESSION['counter']+=1; } <body>
else <?php
{ $_SESSION['counter']=1; } echo($msg);
$msg="You have visited this page ". ?>
$_SESSION['counter']." times in this </body>
session.";
</html>
?>
9/7/2020
Tracking users - Session
• Adding and Reading session data
<?php
session_start();
$_SESSION['firstname']="Advait";
$_SESSION['lastname']="Jain";
$name="My name is ". $_SESSION['firstname']." ".$_SESSION['lastname'].".";
?>
<html> <body>
<?php
echo($name);
?>
</body> </html>
9/7/2020
Tracking users - Session
• Removing session data
<?php
session_start();
$_SESSION['firstname']="Advait";
$_SESSION['lastname']="Jain";
unset($_SESSION['lastname']);// Removing session data.
$name="My name is ". $_SESSION['firstname']." ".$_SESSION['lastname'].".";
?>
<html> <body>
<?php
echo($name);
?>
</body> </html>
9/7/2020
Tracking users - Session
• Ending a session
<html> <body>
<?php
session_start();
if(isset($_SESSION['username']))
{ echo "User :".$_SESSION['username'];
session_destroy(); }
else { echo "set the username :".$_SESSION['username']="Advait"; }
?>
</body> </html>
9/7/2020
PHP Global variables: Supergobals
• Variables which are always accessible , regardless of scope.
• Can be accessible from any function, class or file.
Variable Name Description
$GLOBALS Allows access to global variables from anywhere in PHP script
• Connecting to Database -
• In PHP, you can use database by establishing a connection to the MySQL database
server.
• PHP requires the following information to connect to the database:
• Hostname
• Database username
• Password
9/7/2020
PHP and MySQL database connectivity with example
• Creating a connection with the MySQL Database
<?php
$con=@mysqli_connect("localhost","root","") or die(mysql_error());
echo "connection to the server was successful!";
?>
• Above script displays the text connection to the server was successful! if the
connection with MySQL is established succesfully; else it displays the corresponding
error.
•The mysql_error() function is used to display the MySQL errors.
9/7/2020
PHP and MySQL database connectivity with example
• Creating a Database
<?php
$hostname="localhost";
$user="root";
$password="";
$con=mysqli_connect($hostname,$user,$password) or die(mysql_error());
echo "Connection to the server is successful<br>";
$query="create database employee";
mysqli_query($con,$query) or die(mysql_error($con));
echo "Database created<br>";
?>
• Above script displays the text connection to the server was successful! if the connection
with MySQL is established succesfully; else it displays the corresponding error.
•The mysql_error() function is used to display the MySQL errors.
9/7/2020
PHP and MySQL database connectivity with example
Note: For remaining database operations, please refer shared scripts.
9/7/2020
Thank you
9/7/2020