0% found this document useful (0 votes)
5 views

PHP_Dessalew_Slide_1

Uploaded by

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

PHP_Dessalew_Slide_1

Uploaded by

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

INTERNET

PROGRAMMING II

BY: Dessalew G.
CHAPTER ONE
Introduction

2
List of Contents

◉ Introduction to Server Side Scripting


◉ Server Side Scripting Languages
◉ PHP (Hypertext Preprocessor)
○ Introduction
○ Features of PHP
○ Why PHP
○ PHP Basic Syntaxes

3
Introduction To Server Side Scripting

o Web page is a document, typically written in HTML


that is almost always accessible via HTTP.
o It can be static or dynamic.
o Static web page means that what is displayed does not
change until the underlying HTML or XML is changed.
o When the content that is displayed changes in response
to actions taken by the user, then the web page is said
to be Dynamic.
o Those kind of web pages are developed using
scripting languages. 4
Introduction To Server Side Scripting

◉ Generally, code written in a scripting language does


not have to be compiled – unlike, for example, code
written in C++/Java.
◉ Instead, it is interpreted at the time of execution.
◉ Web browsers can interpret certain scripting
languages.
◉ Scripts can be written to run either server-side or
client-side.
◉ Each scripting language has its own script interpreter –
called a script engine. 5
Introduction To Server Side Scripting

◉ A client-side script is executed on the client, by the


browser.
◉ Client-scripting is often used to validate data entered on a
form by the user, before the form is submitted to the server.
◉ A server-side script is executed on the server, and generally
produces HTML which is then output HTML to the client.
o This enables two-way communication:
o Client to server: Customer-enter information as request.
o Server to client: Web pages can be assembled from back
end-server to give output. 6
How do webserver works?

◉ Client specifies document at a specific web address that is


desired (specified by a URL)
o Ex: http://www.hu.edu.et
◉ If the document is html or text, the server simply forwards it
back to the client
o It is then rendered in the client's browser
◉ However, if it has embedded PHP, the server first executes
the PHP, replacing the PHP code with its output in the
document.

7
How do webserver works?

8
How do webserver works?

◉ The modified document is then sent to the client or web


browser.
◉ The web server does not care what is inside HTML tags,
and sends the entire code to the PHP interpreter, and PHP
would compute that script according to the way it
understands it and sends only the computed result back to
the server, as plain HTML.
◉ All PHP code is executed on a web server only, not on
your local computer.
9
How do webserver works?

◉ For example, if you complete a form on a website and


submit it, or click a link to a web page written in PHP, no
actual PHP code runs on your computer. Instead, the form
data or request for the web page gets sent to a web server
to be processed by the PHP scripts.
o The web server then sends the processed HTML back to
you (which is where 'Hypertext Preprocessor' in the name
comes from), and your web browser displays the results.

10
How do webserver works?

◉ For this reason, you cannot see the PHP code of a website,
only the resulting HTML that the PHP scripts have
produced.

11
Server side scripting languages

◉ There are a number of server-side scripting languages


available, including:
 Python

 PHP(Hypertext Preprocessor)

 ASP(Active Server Pages)

 JSP(Java Server Pages)

 JavaScript using Server-side JavaScript (*.ssjs)

 ColdFusion, Perl, Ruby, and Go, ..

12
PHP (Hypertext Preprocessor)

◉ PHP stands for PHP: Hypertext Preprocessor


◉ PHP is a server-side scripting language.
◉ PHP scripts are executed on the server.
◉ PHP supports many databases (MySQL, Oracle, Sybase,
Solid, Generic ODBC, Microsoft SQL Server etc.)
◉ PHP is an open source software, free to download and use
◉ PHP files may contain text, HTML tags and scripts
◉ PHP files are returned to the browser as plain HTML.
◉ PHP files have a file extension13 of “.php”.
PHP (Hypertext Preprocessor)

◉ PHP is an interpreted language, i.e., there is no need for


compilation, object-oriented scripting language
◉ PHP is faster than other scripting languages, for example,
ASP and JSP.
◉ PHP is simple and easy to learn language.

14
What Can PHP Do?

◉ PHP can generate dynamic page content.


◉ PHP can create, open, read, write, delete, and close files on
the server
◉ PHP can collect form data.
◉ PHP can send and receive cookies.
◉ PHP can add, delete, modify data in your database

◉ PHP can encrypt data.

15
PHP Features

16
Why PHP ?

◉ PHP is a server-side scripting language, which is used to


design the dynamic web applications with MySQL database.
◉ It handles dynamic content, database as well as session
tracking for the website.
◉ You can create sessions in PHP.
◉ It can access cookies variable and also set cookies.
◉ It helps to encrypt the data and apply validation.
◉ PHP supports several protocols such as HTTP, POP3, SNMP,
LDAP, IMAP, and many more.
17
Why PHP ?

◉ Using PHP language, you can control the user to access


some pages of your website.
◉ As PHP is easy to install and setup, this is the main reason
why PHP is the best language to learn.
◉ PHP can handle the forms, such as - collect the data from
users using forms, save it into the database, and return
useful information to the user.
○ For example - Registration form.

18
What you need to get started

◉ To install PHP, you need to install AMP (Apache, MySQL,


PHP) software stack.
◉ It is available for all operating systems. There are many AMP
options available in the market.
◉ Install WAMP server/XAMPP/cross-platform.
◉ MySQL database and PHP programming language.
◉ XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross
Platform:
○ It includes some other components too, such as FileZilla,
OpenSSL, Webalizer, Mercury19
Mail, etc.
What you need to get started

◉ You need some sort of text editor such as Notepad,


Notepad++, Visual studio code, Netbeans, Sublime and etc.
to write the scripts.
◉ The web browser can be Internet Explorer, Mozilla Firefox,
Opera, and Google Chrome etc.

20
How to run PHP programs in XAMPP

◉ These programs save with .php extension, i.e., filename.php


inside the htdocs folder.
○ For example - p1.php.
 So, the path for the htdocs directory will be something like;
“C:\xampp\htdocs".
 Then open the path (URL) of your file on one of your browsers.

21
Using PHP Basic syntax

◉ A PHP scripting block always starts with <?php and ends with ?>.
◉ A PHP scripting block can be placed anywhere in the document.
◉ A PHP script is executed on the server, and the plain HTML
result is sent back to the browser.
<?php
//Body of the script
?>
◉ A PHP file normally contains HTML tags, just like an HTML file,
and some PHP scripting code.
22
PHP Output Statements

◉ There are two basic statements to output text with PHP:


echo and print.
◉ echo can take multiple parameters but print can only take
one argument.
◉ echo is marginally faster than print.
◉ The echo or print statement can be used with or without
parentheses: echo or echo().
◉ The general format of the echo statement is as follows:
o echo outputitem1,outputitem2,outputitem3, . . .;
o echo (output statement); 23
PHP Output Statements

◉ We can pass multiple strings separated by a comma (,) in


echo. Using print, we cannot pass multiple arguments.
◉ The general format of the print statement is as follows:
o print outputstatement; print (outputstatement);
◉ Echo is faster than the print statement.
◉ echo does not return any value.
◉ print always returns an integer value, which is 1.

24
PHP Output Statements

◉ PHP echo statement can be used to print the string, multi-line


strings, escaping characters, variable, array, etc.
<?php
echo "Hello World";// printing string or Display Text
echo "Hello by PHP echo
this is multi line”;// printing multi line string
echo "Hello escape \"sequence\" characters";// printing escaping characters
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
echo "<h2>" . $msg . "</h2>";// printing variable value or Display Variables
?></body></html>. 25
PHP Output Statements

 Each code line in PHP ends with a semicolon.


 The semicolon is a separator and is used to distinguish one
set of instructions from another.

26
PHP Output Statements

<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>"; // displaying text
$txt2 = "W3Schools.com"; echo statement does not return
$x = 5; any value. It will generate an error if you
$y = 4; try to display its return value.
print "Study PHP at " . $txt2 . "<br>"; $lang = "PHP";
print $x + $y; $ret = echo $lang." web development ";
?> echo "</br>";
echo "Value return by print statement: “
.$ret;
<?php Output= errors
$lang = "PHP";
$ret = print $lang." is a web development language.";
print "</br>";
print "Value return by print statement: ".$ret;
27
?>
PHP Comments

 Comment in is a line that is not executed as part of the


program. Its purpose is to be read by someone who is
looking at the code.
 PHP use Three types of comments
1. // or # to make a single-line
2. /* and */ to make multiple Line

28
PHP Comments

<html><head>
<title>comments</title> </head>
<body bgcolor=“#a54353”>
<?php
//This is the first types comment
#This is the second types comment
/* This is the third types comment for multiple line
*/
?>
</body> </html> 29
PHP Variables/Working with Variables

◉ Variables are used for storing values, such as numbers,


strings or function results.
◉ All variables in PHP are denoted with a leading dollar sign
($).
◉ 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.
30
PHP Variables/Working with Variables

 After declaring a variable, it can be reused throughout the


code.
 The value of a variable is the value of its most recent
assignment.
 Variables are assigned with the = operator, with the variable
on the left-hand side and the expression to be evaluated on
the right.

31
Some Rule for Naming Variables

◉ A variable name must start with a letter or an underscore.


◉ A variable must start with a dollar ($) sign, followed by the
variable name.
◉ A variable name can only contain alpha-numeric characters
and underscores (A-Z, 0-9, and _ ) and Variable names are
case-sensitive.
◉ One thing to be kept in mind that the variable name cannot
start with a number or special symbols.

32
Some Rule for Naming Variables

◉ PHP variables are case-sensitive, so $name and $NAME


both are treated as different variable.
◉ A variable name should not contain spaces.
<?php
$varname=“hello world”
Print $varname;
?>

33
Data types

◉ PHP has a total of eight types:


○ Integers are whole numbers, without a decimal point, like
495.
○ Doubles are floating-point numbers, like 3.14159 or 49.0.
○ Booleans have only two possible values: TRUE and
FALSE.
○ Strings are sequences of characters, like “PHP is very
interesting”.
34
Data types

○ Arrays are named and indexed collections of other


values.
○ Objects are instances of programmer-defined classes.
○ Resources are special variables that hold references to
resources external to PHP such as database
connections.
○ NULL is a special type that only has one value: NULL.

35
Data types

◉ PHP allows us to use a variable without declaring its


datatype.
◉ It will be taken automatically at the time of execution based
on the type of data it contains on its value.
◉ This means that a single variable may contain any type of
data.
◉ This could be a number, a string of text, or some other kind
of value, and may change types over its lifetime.

36
Data types

◉ Example:
$testvar = 3 + 4;
echo “The value is $testvar”; //output: The value
is 7
$testvar = “three”;
echo “The value is $testvar”; //output: The value
is three

37
Displaying variable values

◉ You can display the value stored in a variable with print


statement:
$today = “Sunday”;
print(“The day today is $today”);
◉ The output from the preceding statements is “The day
today is Sunday”.
Removing Variables
◉ You can uncreate the variable by using this statement:
unset($age); 38
Displaying variable values

◉ After this statement, the variable $age no longer exists.


◉ If you try to echo it, you get an “undefined variable” notice.
◉ You can unset more than one variable at once, as follows:
unset($age, $name, $address);

39
Checking Variable Content

◉ Sometimes you just need to know whether a variable exists


or what type of data is in the variable.
◉ Here are some common ways to test variables:
○ isset($varname) - is used to determine that a variable is
set or not.
◉ You can also test what type of data is in the variable.
○ For example, to see if the value is an integer:
■ is_int($number) - the comparison is TRUE if the value
in $number is an integer.
40
Checking Variable Content

○ is_integer($var): same as is_int($var)


○ is_array($var2): Checks to see if $var2 is an array
○ is_float($number): Checks if $number is a floating point
number
○ is_null($var1): Checks to see if $var1 is equal to NULL
or not.
○ is_numeric($string): Checks to see if $string is a
numeric string
○ is_string($string): Checks to see if $string is a string
○ is_bool($var): finds out whether a variable is a boolean
41
Checking Variable Content

◉ You can test for a negative, as well, by using not operator


(!) in front of the expression.
◉ For example, the following statement returns TRUE if the
variable does not set with value:
!isset($varname)

42
Checking Variable Content

<?php
$a = "test";
$b = "anothertest";
echo isset($a); // TRUE
echo isset($a, $b); //TRUE
unset ($a); //cleared/removed so it undefined
echo isset($a, $b); //FALSE
$foo = NULL;
print isset($foo); // FALSE
$var = 0;
if (empty($var)) // evaluates TRUE
echo '$var is either 0 or not set at all';
?> 43
Type Casting

◉ Converting one data type to another one is a common task in


programming.
◉ Type conversion or typecasting refers to changing a variable of one
data type into another.
◉ There are two types of conversion.
○ Implicit and
○ Explicit
◉ Implicit type conversion is an automatic type conversion by the
compiler.
◉ Example:
echo "45" + 12; //output: 57
echo 12 + 12.4; //output: 24.4 44
Type Casting

◉ Explicit conversion happens, when we use the cast constructs.


◉ There are two ways to do this:
○ Using bool settype ( mixed var, string type) function
○ Using cast methods
◉ The cast methods are:
○ (int), (integer) - cast to integer
○ (bool), (boolean) - cast to boolean
○ (float), (double), (real) - cast to float
○ (string) - cast to string
○ (array) - cast to array
○ (object) - cast to object
45
Type Casting

◉ Settype sets the type of a variable.


◉ The syntax is:
bool settype ( mixed var, string type)
◉ Possible values of type are:
○ "boolean"
○ "integer"
○ "float"
○ "string"
○ "array"
○ "object"
○ "null"
46
Type Casting

$foo = "321.456number";
settype($foo, "float");
print("<br>Float: $foo"); //output: Float: 321.456
$foo = "321.456number";
settype($foo, "integer");
print("<br>Integer: $foo"); //output: Integer: 321
$foo = 321.456;
settype($foo, "string");
print("<br>String: $foo"); //output: String: 321.456

$foo = “10.7S”; // $foo is string


$bar = (float) $foo; // $bar is float
$val = (int) $foo; //$val is int
47
PHP Global Variables- Superglobals

◉ These are specially-defined array variables in PHP that


make it easy for you to get information about a request or
its context.
◉ 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.
◉ They are mainly used to store and get information from
one page to another etc in an application.
48
PHP Global Variables- Superglobals

◉ $GLOBALS — used to access global variables from


anywhere in the PHP script.
○ $_SERVER — It is a PHP super global variable that
stores the information about headers, paths and script
locations
○ $_GET — used to collect data from the HTML form
after submitting it
○ $_POST— used to collect data from the HTML form
after submitting it
49
PHP Global Variables- Superglobals

○ $_FILES — It can be used to upload files from a client


computer/system to a server.
○ $_REQUEST — used to collect the data after submitting
a HTML form
○ $_SESSION — A session variable is used to store
information about a single user, and are available to all
pages within one application.
○ $_COOKIE — A cookie is used to identify a user. cookie
is a small file that the server embedded on user
computer.
50
PHP Variables Scope:

◉ Scope can be defined as the range of availability a variable


has to the program in which it is declared.
◉ The scope of a variable is defined as its range in the
program under which it can be accessed.
◉ In other words, "The scope of a variable is the portion of the
program within which it is defined and can be accessed."
◉ PHP variables can be one of three scope types:
○ Local variables
○ Global variables
○ Static variables 51
PHP Local Variables

◉ The variables that are declared within a function are


called local variables for that function.
◉ These local variables have their scope only in that
particular function in which they are declared.
◉ This means that these variables cannot be accessed
outside the function, as they have local scope.
◉ A variable declaration outside the function with
the same name is completely different from the
variable declared inside the function.
52
PHP Local Variables

<?php
function local_var()
{ <?php

$num = 45; //local variable


function mytest() {
$lang = "PHP";
echo "Local variable declared inside the
echo "Web development language: "
.$lang;
function is: ". $num; }
mytest();
} //using $lang (local variable) outside
local_var(); the function will generate an error
echo $lang;
?> ?>

53
PHP Global Variables

◉ The global variables are the variables that are declared


outside the function. These variables can be accessed
anywhere in the program.
◉ To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these
variables can be directly accessed or used outside the
function without any keyword.
◉ Therefore there is no need to use any keyword to access a
global variable outside the function.
54
PHP Global Variables

• Let's understand the global variables with the help of an


example:
<?php <?php
$name = "Sanaya Sharma"; //Global Variable $name = "Sanaya Sharma";
//global variable
function global_var() { function global_var()
global $name; {
echo "Variable inside the function: ". $name; echo "Variable inside the
echo "</br>"; } function: ". $name;
echo "</br>";
global_var(); }
echo "Variable outside the function: ". $name; global_var();
?> ?>
55
PHP Global Variables

◉ Using $GLOBALS instead of global


○ Another way to use the global variable inside the
function is predefined $GLOBALS array.
■ PHP also stores all global variables in an array
called $GLOBALS[index].
■ The index holds the name of the variable.
■ This array is also accessible from within functions
and can be used to update global variables directly.

56
PHP Global Variables

◉ The example above can be rewritten like this:


<?php
$num1 = 5; //global variable
$num2 = 13; //global variable
function global_var()
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>

◉ Note: If two variables, local and global, have the same


name, then the local variable has higher priority than the
57
PHP Static Variables

◉ It is a feature of PHP to delete the variable, once it


completes its execution and memory is freed.
◉ Sometimes we need to store a variable even after
completion of function execution.
◉ Therefore, another important feature of variable scoping is
static variable.
◉ We use the static keyword before the variable to define a
variable, and this variable is called as static variable.

58
PHP Static Variables

◉ It is a feature of PHP to delete the variable, once it


completes its execution and memory is freed.
◉ Sometimes we need to store a variable even after
completion of function execution.
◉ Therefore, another important feature of variable scoping is
static variable.
◉ We use the static keyword before the variable to define a
variable, and this variable is called as static variable.

59
PHP Static Variables

 Static variables exist only in a local function, but it does not


free its memory after the program execution leaves the
scope
 In contrast to the variables declared as function
parameters, which are destroyed on the function's exit, a
static variable will not lose its value when the function exits
and will still hold that value should the function be called
again.

60
PHP Static Variables

<?
function keep_track() {
STATIC $count = 0;
$count++; // print $count; then $count++;
print $count;
print “<br> "; This will produce the following result.
1
} 2
keep_track(); 3
Then, each time the function is called,
keep_track(); that variable will still have the information
keep_track(); it contained from the last time the
function was called.
?> 61
PHP Static Variables

Example:
<?php
function static_var() {
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in static variable You have to notice that $num1
$num1++; regularly increments after each
//increment in non-static variable function call, whereas $num2
$num2++;
echo "Static: " .$num1 ."</br>";
does not.
echo "Non-static: " .$num2 ."</br>"; This is why because $num2 is
} not a static variable, so it freed its
//first function call memory after the execution of
static_var();
//second function call
each function call.
static_var(); ?> 62
Working with Constants

◉ A constant is a name or an identifier for a simple value.


◉ A constant value cannot change during the execution of
the script.
◉ By default a constant is case-sensitive. By convention,
constant identifiers are always uppercase.
◉ A constant name starts with a letter or underscore,
followed by any number of letters, numbers, or
underscores.
◉ If you have defined a constant, it can never be changed or
undefined. 63
Working with Constants

◉ To define a constant you have to use define() function


and to retrieve the value of a constant, you have to simply
specifying its name.
◉ Unlike with variables, you do not need to have a constant
with a $.
◉ You can also use the function constant() to read a
constant's value if you wish to obtain the constant's name
dynamically.

64
Working with Constants

◉ We use constants to define values that do not change like


PI in maths(3.14..), number of days in a week(7), number of
minutes in an hour(60), etc.
◉ Constants are set by using the define statement.
◉ The general format is as follows:
define(“constantname”, ”constantvalue”);
◉ For example:
define(“PI”,”3.141”);
◉ This statement creates a constant called PI and sets its
value to “3.141”. 65
Working with Constants

◉ You can determine the value of a constant by using echo


as follows:
echo INTEREST;

◉ When you echo a constant, you can’t enclose it in quotes.


◉ You can build more complicated output statements by
using commas, as in the following example:
◉ echo “The Canadian exchange rate is $”, INTEREST
66
Working with Constants
◉ constant() function
 As indicated by the name, this function will return the value of
the constant.
 This is useful when you want to retrieve value of a constant, but
you do not know its name, i.e. It is stored in a variable or
returned by a function.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
◉ Only scalar data (Boolean, integer, float and string) can be
contained in constants. 67
Differences Between Constants and Variables

◉ There is no need to write a dollar sign ($) before a


constant, where as in Variable one has to write a dollar
sign.
◉ Constants cannot be defined by simple assignment, they
may only be defined using the define() function.
◉ Constants may be defined and accessed anywhere
without regard to variable scoping rules.
◉ Once the Constants have been set, may not be redefined
or undefined.
68
Using Operators

◉ PHP supports many operators.


Mathematical Operators
◉ Arithmetic operators are straightforward—they are just the
normal mathematical operators.
Operator Description
+ Adds two numbers together.
- Subtracts the second number from the first number.
* Multiplies two numbers together.
/ Divides the first number by the second number.
% Finds the remainder when the first number is divided by the
second number. 69
Using Operators

◉ a program that performs all mathematical


operation on two numbers
$a = 10;
$b = 20;
$c = $a + $b; //result: 30
$c = $a - $b; //result: -10
$c = $a * $b; //result: 200
$c = $a / $b; //result: 0.5
$c = $a % $b; //result: 10
70
Pre- and Post-Increment and Decrement operators

operator description example meaning


++ postfix increment $x++ $x = $x+1
-- postfix decrement $x-- $x = $x-1
++ prefix increment ++$x $x = $x+1
-- prefix decrement --$x $x = $x-1
◉ Example: a program that performs postfix and prefix operations
$a = 4;
echo “<br>”, ++$a;
$b = 10;
echo “<br>”, $b++;
71
echo “<br>”, $b;
Pre- and Post-Increment and Decrement operators

◉ All the increment operators have two effects—they


increment and assign a value.
$a=4;
echo ++$a;
◉ The second line uses the prefix increment operator.
◉ In this case, $a is incremented to 5 and then the value 5 is
returned and printed.
◉ This has a different effect.
$a=4;
echo $a++; 72
Pre- and Post-Increment and Decrement operators

◉ In this case, first, the value of $a is returned and printed,


and second, it is incremented.
◉ The value that is printed is 4.
◉ However, the value of $a after this statement is executed
is 5.

73
Pre- and Post-Increment and Decrement operators

Operator description example meaning

+= add and assign $x += 5 $x = $x + 5

-= subtract and assign $x -= 5 $x = $x – 5

/= divide and assign $x /= 5 $x = $x / 5

*= multiply and assign $x *= 5 $x = $x * 5

%= modulate and assign $x %= 5 $x = $x % 5

.= concatenate and assign $x .= " test" $x = $x." test"

74
Comparison Operators

◉ The comparison operators are used to compare two values. TRUE/FALSE


operator name description
== equal True if its arguments are equal to each other, false otherwise
!= not equal False if its arguments are equal to each other, true otherwise
< less than True if the left-hand argument is less than its right-hand argument, but false
otherwise
> greater than True if the left-hand argument is greater than its right-hand argument, but
false otherwise
<= less or equal True if the left-hand argument is less than its right-hand argument or equal to
it, but false otherwise
>= greater or equal True if the left-hand argument is greater than its right- hand argument or
equal to it, but false otherwise
=== identical True if its arguments are equal to each other and of the same type, but false
75
otherwise
Comparison Operators

<?php
$var = "30";
$num = 30;
if($var == $num)
print "They are equal.<br>";
if($var === $num)
print "They are equal and same data type.<br>";
$var = (int) “30”;
if($var === $num) Output:
They are equal
print "2. They are equal and same data type.<br>";
2. They are equal and same data type.
?> 76
Logical Operators

◉ The logical operators are used to combine the results of logical conditions.
operator description

and Is true if and only if both of its arguments are true

or Is true if either (or both) of its arguments are true.

xor Is true if either (but not both) of its arguments are true

! Is true if its single argument (to the right) is false and false if its argument is
true
&& Same as and

|| Same as or
77
The Ternary operator

◉ It plays a role somewhere between a Boolean operator


and a true branching construct.
◉ Its job is to take three expressions and use the truth value
of the first expression to decide which of the other two
expressions to return.
◉ The syntax looks like:
test-expression ? yes-expression : no-expression

78
The Ternary operator

◉ The value of this expression is the result of yes-expression


if test-expression is true; otherwise, it returns no-expression.
◉ For example, assigning to $max either $first or $second,
whichever is larger:
$max_num = $first > $second ? $first : $second;

79
PHP Strings

◉ A string is a sequence of characters.


◉ Tasks commonly associated with strings in PHP are
removing unnecessary whitespace, finding and replacing
string patterns, counting and extracting string segments.
Controlling String Case
◉ Use the strtoupper() or strtolower() functions to change into
uppercase and lowercase respectively
◉ Use the Ucfirst() to make a string's first character
uppercase
80
PHP Strings

◉ Reversing Strings
○ Use the strrev() function reverses a string
◉ Counting Words in a String
○ Use str_word_count() function counts the number of
words in a string
◉ length of the string
○ Use strlen() Function returns the length of a string.
◉ Replace Text Within a String
○ The PHP str_replace() function replaces some characters
with some other characters 81
in a string.
PHP Strings

<?php
echo str_replace("world","Peter","Hello world!");
?>
◉ To concatenate use dot (.)
<? php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
82
PHP Strings

<?php
// Input string
$subjectVal = "It was nice meeting you. May you shine
bright.";
// Using str_replace() function
$resStr = str_replace('you', 'him', $subjectVal);
print_r($resStr); ?>
83
PHP Strings

 This example describes replacing all the search strings with


replacing strings using the str_replace()
<?php
// Input string
$str = "You eat fruits, vegetables, fiber every day.";
// Array containing search string
$searchVal = array("fruits", "vegetables", "fiber");
// Array containing replace string from search string
$replaceVal = array("pizza", "beer", "ice cream");
// Function to replace string
$res = str_replace($searchVal, $replaceVal, $str); print_r($res);
?> 84
Manipulating Number in PHP

◉ Rounding a Floating Point Number


○ Use the round() function:
◉ Convert a number to a different base
○ To convert number to different base use
■ decbin() from decimal to binary
■ decoct() from decimal to octal
■ dexhec() from decimal to hexadecimal
■ base_convert() from decimal to convert one base to
another
◉ Generating Random Numbers
○ Use PHP’s rand() function 85
Use Conditionals

◉ Very often when you write code, you want to perform


different actions for different conditions.
◉ You can use conditional statements in your code to do this.
◉ 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 86
Use Conditionals

◉ switch statement - selects one of many blocks of code to


be executed

◉ The if statement executes some code if one condition is


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

87
Use Conditionals

$num=12;
if($num<100){
echo "$num is less than 100";
}

<?php
$date = date("H");
if ($date<20) Output "Have a good day!"
{ if the current time (HOUR)
echo "have a good day"; is less than 20:
}
?>
88
Use Conditionals

◉ 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.
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
} 89
Use Conditionals

<?php
$t = date("H");//");//24-hour format of an hour (00 to 24)
if ($t < "20") { Output "Have a good day!" if the
echo "Have a good day!"; current time is less than 20, and
} else { "Have a good night!" otherwise:
echo "Have a good night!";
} <?php Note: The date() function
?> $num=12; formats a local date and time,
if($num%2==0){
echo "$num is even number";
and returns the formatted
}else{ date string.
echo "$num is odd number";
} ?> 90
Use Conditionals

◉ 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
91
}
Use Conditionals

$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") { Output "Have a good morning!" if the
echo "Have a good day!"; current time is less than 10,
and "Have a good day!“
} else { if the current time is less than 20.
echo "Have a good night!"; Otherwise it will output "Have a good night!":

}
92
Use Conditionals

◉ PHP switch statement is used to execute one statement


from multiple conditions.
◉ It works like PHP if-else-if statement.
◉ The switch statement is used to perform different actions
based on different conditions.
○ Use the switch statement to select one of many blocks
of code to be executed.

93
Use Conditionals

switch (expression)
{
case label1:
code to be executed if expression =label1;
break;
case label2:
code to be executed if expression =label2;
break;
...
default:
code to be executed if expression is different from all labels;}
94
Use Conditionals

◉ This is how it works: First we have a single expression such


as n (most often a variable), that is evaluated once.
◉ The value of the expression is then compared with the
values for each case in the structure.
◉ If there is a match, the block of code associated with that
case is executed. Use break to prevent the code from
running into the next case automatically.
◉ The default statement is used if no match is found.
◉ Each case can have a break statement, which is used to
terminate the sequence of statement.
95
Use Conditionals

◉ The default is an optional statement. Even it is not


important, that default must always be the last statement.
◉ There can be only one default in a switch statement.
◉ More than one default may lead to a Fatal error.
◉ Each case can have a break statement, which is used to
terminate the sequence of statement.
◉ PHP allows you to use number, character, string, as well as
functions in switch expression.

96
Use Conditionals

◉ Nesting of switch statements is allowed, but it makes the


program more complex and less readable.
◉ You can use semicolon (;) instead of colon (:). It will not
generate any error.

97
Use Conditionals

<?php <?php
$favcolor = "red"; $num=20;
switch ($favcolor) { switch($num){
case "red": case 10:
echo "Your favorite color is red!"; echo("number is equals to 10");
break;
break;
case "blue":
echo "Your favorite color is blue!"; case 20:
break; echo("number is equal to 20");
default: break;
echo "Your favorite color is default:
neither red, blue, nor green!"; echo("number is not equal to 10, 20
}?> 98
or 30");}?>
PHP Loops

◉ PHP for loop can be used to traverse/navigate 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.
◉ It allows users to put all the loop related statements in one
place. See in the syntax given below:
for(initialization; condition; increment/decrement){
//code to be executed
99
}
PHP Loops

◉ initialization - Initialize the loop counter value. The initial


value of the for loop is done only once.
◉ condition - Evaluate each iteration value. The loop
continuously executes until the condition is false. If TRUE,
the loop execution continues, otherwise the execution of
the loop ends.
◉ Increment/decrement - It increments or decrements the
value of the variable.
for($n=1;$n<=10;$n++) {
echo "$n </br>"; } 100
PHP Loops

◉ PHP while loop can be used to traverse set of code like for
loop.
◉ The while loop executes a block of code repeatedly until
the condition is FALSE. Once the condition gets FALSE, it
exits from the body of loop.
◉ It should be used if the number of iterations is not known.
◉ 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
101 code will be executed.
PHP Loops

while(condition){ While (condition):


//code to be executed
//code to be executed endwhile;
$n=1;
} while($n<=10):
echo "$n<br/>";
$n=1; $n++;
endwhile;
while($n<=10) { Below is the example of printing alphabets using
while loop.
echo "$n </br>"; $i = 'A';
while ($i < 'H') {
$n++; } echo $i;
$i++;
echo "</br>"; }

102
PHP Loops

◉ PHP do-while loop can be used to traverse set of code like


php while loop. The PHP do-while loop is guaranteed to
run at least once.
◉ The PHP do-while loop is used to execute a set of code of
the program several times. If you have to execute the loop
at least once and the number of iterations is not even fixed,
it is recommended to use the do-while loop.
◉ It executes the code at least one time always because the
condition is checked after executing the code.
103
PHP Loops

◉ The do-while loop is very much similar to the while loop


except the condition check. The main difference between
both loops is that while loop checks the condition at the
beginning, whereas do-while loop checks the condition at
the end of the loop. $n=1;
do{ do
//code to be executed {
echo "$n </br>";
}while(condition); $n++;
}
while($n<=10);
104
PHP Loops

105
PHP Loops

 PHP break statement breaks the execution of the current


for, while, do-while, and switch.
 If you use break inside inner loop, it breaks the execution of
inner loop only.
 The break keyword immediately ends the execution of the
loop or switch structure.
 It breaks the current flow of the program at the specified
condition and program control resumes at the next
statements outside the loop.
106
PHP Loops

◉ Let's see a simple example to break the execution of for


loop if value of i is equal to 5:
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}}

107
PHP Array

◉ PHP array is an ordered map (contains value on the basis of


key).
◉ It is used to hold multiple values of similar type in a single
variable.
◉ There are 3 types of array in PHP.
○ Indexed Array
○ Associative Array
○ Multidimensional Array

108
PHP Array

◉ PHP Indexed Array


○ PHP index is represented by number which starts from 0.
○ We can store number, string and object in the PHP array.
○ All PHP array elements are assigned to an index number
by default.
○ There are two ways to define indexed array:
■ $season=array("summer","winter","spring","autumn");
■ $season[0]="summer"; $season[1]="winter";

109
PHP Array

<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
<?php

<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
110
PHP Array

◉ An associative array, each ID key is associated with a value.


◉ With associative arrays we can use the values as keys and assign
values to them.
◉ We can associate name with each array elements in PHP using =>
symbol.
◉ There are two ways to define associative array:
◉ $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"2000
00");
◉ $salary["Sonoo"]="350000"; $salary["John"]="450000"; $salary["Kar
tik"]="200000"; 111
PHP Array

<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";$salary["Sonoo"]="350000";
$salary["John"]="450000";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
$salary["Kartik"]="200000";
?> echo "Sonoo salary:
".$salary["Sonoo"]."<br/>";
echo "John salary:
".$salary["John"]."<br/>";
echo "Kartik salary:
".$salary["Kartik"]."<br/>";
112
Create a Simple Form using PHP

<?php
echo “<form action=’login.php’ method=’POST’>\n
<input type=’text’ name=’Username’ />\n
<input type=’password’ name=’Passwd’ />\n
<input type=’submit’ value=’Login’ />\n
</form>\n”;
?>

113
Create a simple Form using HTML

<form action=”login.php” method=”POST”>


<input type=”text” name=”username” />
<input type=”passowrd” name=”passwd” />
<input type=”submit” value=”Login” />
</form>

114
Get and Post Methods in PHP

◉ PHP provides two methods through which a client (browser)


can send information to the server. These methods are:
○ GET method and
○ POST method
◉ Get and Post methods are the HTTP request methods used
inside the <form> tag to send form data to the server.
◉ 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.
115
Get and Post Methods in PHP

◉ 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.
○ localhost/gettest.php?username=Harry&bloodgroup=AB+
116
Get and Post Methods 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.

117
Get and Post Methods in PHP

◉ 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 word118documents) to the server.
Get and Post Methods in PHP

 Similar to the GET method, the 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.
119
Get and Post Methods 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 not visible to anyone.
○ There is no limitation on size of data to be sent using the
POST Method. You can send a large amount of
information using this method.
○ Binary and ASCII data can also be sent using the POST
method.

120
Get and Post Methods in PHP

○ Data security depends on the HTTP protocol because


the information sent using the POST method goes
through the HTTP header.
○ By using secure HTTP, you can ensure that your data is
safe.
◉ Disadvantages of POST Method
○ POST requests do not cache.
○ POST requests never remain in the browser history.
○ It is not possible to bookmark the page because the
variables are not displayed in URL.
121
Get and Post Methods in PHP

◉ $_REQUEST variable
○ The $_REQUEST variable is a superglobal variable,
which can hold the content of both $_GET and $_POST
variable.
○ In other words, the PHP $_REQUEST variable is used to
collect the form data sent by either GET or POST
methods.
○ It can also collect the data for $_COOKIE variable
because it is not a method-specific variable.

122
Get and Post Methods in PHP

<?php
echo “User Name ". $_REQUEST[‘uname']. "<br />";
echo “Password ". $_REQUEST[‘passwd']. " ";
?>
<form action=“pos.php" method=“POST/GET">
User Name: <input type="text" name=“uname" />
Password: <input type=“password" name=“passwd" />
<input type="submit" />
</form> 123

You might also like