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

DOC-20250213-WA0018.

PHP is an open-source, server-side scripting language ideal for web development, known for its speed and ease of use. It supports various databases and allows for dynamic content management, session tracking, and cookie handling. PHP features include variable scope, data types, conditional statements, and the ability to embed code within HTML.
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)
10 views

DOC-20250213-WA0018.

PHP is an open-source, server-side scripting language ideal for web development, known for its speed and ease of use. It supports various databases and allows for dynamic content management, session tracking, and cookie handling. PHP features include variable scope, data types, conditional statements, and the ability to embed code within HTML.
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/ 202

Introduction to PHP

PHP Introduction
PHP is an open-source, interpreted, and object-
oriented scripting language that can be executed
at the server-side..

PHP is well suited for web development.


 PHP stands for Hypertext Preprocessor.
 PHP is an interpreted language, i.e., there is no
need for compilation.
 PHP is faster than other scripting languages,
for example, ASP and JSP.
 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.
PHP Introduction

> PHP scripts are executed on the server


PHP supports many databases

 MySQL
 Informix
 Oracle
 Sybase,
 PostgreSQL,
 Generic ODBC,
PHP Introduction

< PHP runs on different platforms )Windows,


Linux, Unix, etc.)
< PHP is compatible with almost all servers used
today )Apache, IIS, etc.)
> PHP is FREE to download from the official PHP
resource: www.php.net
> PHP is easy to learn and runs efficiently on the
server side
PHP Introduction
Some info on MySQL which we will cover in the next workshop...

> MySQL is a database server


> MySQL is ideal for both small and large
applications
> MySQL supports standard SQL
> MySQL compiles on a number of platforms
> MySQL is free to download and use
Why use 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.
Why use PHP
 PHP supports several protocols such as HTTP,
POP3, SNMP, LDAP, IMAP, and many more.
 Using PHP language, you can control the user
to access some pages of your website.
 As PHP is easy to install and set up, 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.
PHP Features
PHP Syntax
 PHP file contains HTML tags and some PHP scripting
code.
 All PHP code goes between the php tag. It starts with

<?php

//your code here

?> and ends with


PHP Hello World
1.<html>
2.<body>
3.<?php
4.echo "<h2>Hello First PHP</h2>";
5.?>
6.</body>
7.</html>
PHP Hello World

It renders as HTML that looks like this:


PHP Hello World

This program is extremely simple and you really


did not need to use PHP to create a page like this.
All it does is display: Hello World using the PHP
echo() statement.

Think of this as a normal HTML file which


happens to have a set of special tags available to
you that do a lot of interesting things.
PHP Comments
 PHP comments can be used to describe
any line of code so that other developer
can understand the code easily.
 It can also be used to hide any code.
 PHP supports single line and multi line
comments.
 These comments are similar to C/C++
and Perl style (Unix shell style)
comments.
PHP Single Line Comments

There are two ways to use single line


comments in PHP.
1. // (C++ style single line comment)
2. # (Unix Shell style single line
comment)
<?php
// this is C++ style single line comment
# this is Unix Shell style single line comment
echo "Welcome to PHP single line comments";
?>
PHP Multi Line Comments
 In PHP, we can comments multiple lines also.
 To do so, we need to enclose all lines within /* */.

example of PHP multiple line comment.

<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
PHP Case Sensitivity
 In PHP, keyword (e.g., echo, if, else,
while), functions, user-defined
functions, classes are not case-
sensitive.
 all variable names are case-sensitive
Hello world using echo Hello world using ECHO Hello world using EcHo

Example
<html>
<body>
<?php
echo "Hello world using echo </br>";
ECHO "Hello world using ECHO </br>";
EcHo "Hello world using EcHo </br>";
?>
</body>
</html>
Look at the below example that the variable
names are case sensitive
<html>
<body>
<?php
$color = "black";
echo "My car is ". $ColoR ."</br>";
echo "My dog is ". $color ."</br>";
echo "My Phone is ". $COLOR ."</br>";
?>
</body>
</html>
PHP Variables
> Variables are used for storing values, like text
strings, numbers or arrays.
> When a variable is declared, it can be used
over and over again in your script.
> All variables in PHP start with a $ sign symbol.
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 data type.
 After declaring a variable, it can be reused
throughout the code.
 Assignment Operator (=) is used to assign the
value to a variable.
PHP Variables

> A variable name must start with a letter or an


underscore "_" -- not a number
< A variable name can only contain alpha-numeric
characters, underscores )a-z, A-Z, 0-9, and _ )
< A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with an underscore )$my_string( or with
capitalization )$myString)
PHP Variable: Declaring string, integer, and float
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
PHP Variable Scope

 The scope of a variable is defined as its range


in the program under which it can be
accessed.
 The scope of a variable is the portion of the
program within which it is defined and can be
accessed.
 PHP has three types of variable scopes:
1) Local variable
2) Global variable
3) Static variable
Local variable

 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.
 these variables cannot be accessed outside
the function, as they have local scope.
Example
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the func
tion is: ". $num;
}
local_var();
?>
Example 2
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
//using $lang (local variable) outside the function will generate an error

echo $lang;
?>
Global variable
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.
These variables can be directly accessed or used
outside the function without any keyword
Example:
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Example:2
<?php
$name = "Sanaya Sharma"; //global variable
function global_var()
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>
Using $GLOBALS instead of global
 Another way to use the global variable inside the
function is predefined $GLOBALS array.
<?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();
?>
What Happen
 If two variables, local and global, have the
same name,
 then the local variable has higher priority than
the global variable inside the function.
<?php
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Static variable
 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.
 Static variables exist only in a local function,
but it does not free its memory after the
program execution leaves the scope.
Example
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
$num1++; //increment in non-static variable
$num2++; //increment in static variable
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
static_var(); //first function call
static_var(); //second function call
?>
PHP Concatenation
> The concatenation operator (.) is used to put
two string values together.
> To concatenate two string variables together,
use the concatenation operator:
PHP Concatenation

The output of the code on the last slide will be:

If we look at the code you see that we used the


concatenation operator two times. This is
because we had to insert a third string (a space
character), to separate the two strings.
PHP Constants
 PHP constants are name or identifier that can't be changed
during the execution of the script except for magic
constants
 PHP constants can be defined by 2 ways:
1. Using define() function
2. Using const keyword
 Constants are similar to the variable except once they
defined, they can never be undefined or changed.
 They remain constant across the entire program.
 PHP constants follow the same PHP variable rules.
PHP constant: define()
Use the define() function to create a constant. It defines
constant at run time. Let's see the syntax of def in e()
function in PHP.

define(name, value, case-insensitive)


 name: It specifies the constant name.

 value: It specifies the constant value.

 case-insensitive: Specifies whether a constant is case-


insensitive. Default value is false. It
means it is case sensitive by
default.
Example
Create a constant with case-insensitive name:
<?php
define("MESSAGE","Hello JavaTpoint PHP",
true);
//not case sensitive
echo MESSAGE, "</br>";
echo message;
?>
Create a constant with case-sensitive name:
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);
//case sensitive
echo MESSAGE;
echo message;
?>
PHP constant: const keyword
 PHP introduced a keyword const to create a
constant.
 The const keyword defines constants at compile
time.
 It is a language construct, not a function.
 The constant defined using const keyword are case-
sensitive.

<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Magic Constants
Magic constants are the predefined constants in PHP.
They start with double underscore (__) and ends with double
underscore.
They are similar to other predefined constants but as they
change their values with the context, they are called magic
constants.
There are nine magic constants in PHP. In which eight magic
constants start and end with double underscores (__).
1) _ _LINE_ _ 2) __FILE__ 3) __DIR__

4) __FUNCTION__ 5) __CLASS__ 6) __TRAIT__

7) __METHOD__ 8) __NAMESPACE__ 9) ClassName::class


PHP 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:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
PHP Data Types: Scalar Types
Constant vs Variables
PHP Operators
Comparison Operators
Comparison operators allow comparing two values, such as number or string.
Below the list of comparison operators are given:
PHP Conditional Statements

> Very often when you write code, you want to


perform different actions for different decisions.
> You can use conditional statements in your
code to do this.
> In PHP we have the following conditional
statements...
PHP Conditional Statements
> if statement - use this statement to execute
some code only if a specified condition is true
> if...else statement - use this statement to
execute some code if a condition is true and
another code if the condition is false
> if...elseif....else statement - use this statement
to select one of several blocks of code to be
executed
> switch statement - use this statement to select
one of many blocks of code to be executed
PHP Conditional Statements
If Statement
It is executed if condition is true.

Syntax:

if(condition)
{
//code to be executed
}
Example
<?php
$num=12;
if($num<100)
{
echo "$num is less than 100";
}
?>
PHP Conditional Statements
Use the if....else statement to execute some code if a condition is
true and another code if a condition is false.

Syntax
if(condition)
{
//code to be executed if true
}
Else
{
//code to be executed if false
}
Example
<?php
$num=12;
if($num%2==0)
{
echo "$num is even number";
}
else
{
echo "$num is odd number";
}
?>
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.

Syntax:
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 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
}
}
Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18)
{
echo "Eligible to give vote";
}
else
{
echo "Not eligible to give vote";
}
}
?>
PHP Conditional Statements
PHP switch
 PHP switch statement is used to execute one statement from multiple conditions.
 It works like PHP if-else-if statement.
Important points to be noticed about switch case:
 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.
 The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
 PHP allows you to use number, character, string, as well as functions in switch
expression.
 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.
Switch Flowchart
Loops in PHP
for Loop

PHP for loop can be used to traverse set of code for the
specified number of times.

Syntax:

for(initialization; condition;
increment/decrement)
{
//code to be executed
}
initialization -
 Initialize the loop counter value.
 The initial value of the for loop is done only
once.
 This parameter is optional.
condition -
 The loop execution depend on condition.
 If TRUE, the loop execution continues,
otherwise the execution of the loop ends.
Increment/decrement -
 It increments or decrements the value of
the variable.
Example

<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>
foreach loop
 The foreach loop is used to traverse the array elements.
 It works only on array and object.
 It will issue an error if you try to use it with the variables of
different datatype.
 The foreach loop works on elements basis rather than index.
 It provides an easiest way to iterate the elements of an array.
 In foreach loop, we don't need to increment the value.

Syntax:

<?php
foreach( $array as $var )
{
//code to be executed
}
?>
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr )
{
echo "Season is: $arr<br />";
}
?>
While Loop
 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.
 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.

Syntax Alternative Syntax

while(condition) while(condition):
{
//code to be executed
//code to be executed
}
endwhile;
<?php
$i = 'A';
while ($i < 'H')
{
echo $i;
$i++;
echo "</br>";
}
?>
While Loop Example
<?php
$n=1;
while($n<=10)
{
echo "$n<br/>";
$n++;
}
?>
do-while loop
 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
 It executes the code at least one time always because the condition is
checked after executing the code.

Syntax

do
{
//code to be executed
}while(condition);
Example

<?php
$x = 1;
do {
echo "1 is not greater than 10.";
echo "</br>";
$x++;
} while ($x > 10);
echo $x;
?>
PHP Arrays

> A variable is a storage area holding a number or


text. The problem is, a variable will hold only one
value.
> An array is a special variable, which can store
multiple values in one single variable.
PHP Array Types

There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP Indexed Array/Numeric Arrays

 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:


1st way:

$season=array("summer","winter","spring","autumn");

2nd way:

$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example

<?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]";
?>

Output:
Season are: summer, winter, spring and autumn
PHP Associative Arrays
 With an associative array, each ID key is
associated with a value.
 We can associate name with each array
elements in PHP using => symbol.
Two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";

$salary["Kartik"]="200000";
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>

<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
PHP Multidimensional Arrays

 PHP multidimensional array is also


known as array of arrays.
 It allows you to store tabular data in
an array.
 PHP multidimensional array can be
represented in the form of matrix
which is represented by row * column.
PHP Multidimensional Arrays

$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Example
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

for ($row = 0; $row < 3; $row++) {


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Array Functions
 PHP provides various array functions to access and manipulate the elements of
array. The important PHP array functions are given below.

1) PHP array() function

 PHP array() function creates and returns an array. It allows


you to create indexed, associative and multidimensional
arrays.

Syntax
array array ([ mixed $... ] )
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
2) PHP array_change_key_case() function
PHP array_change_key_case() function changes the
case of all key of an array.

Note: It changes case of key only.

Syntax

array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>

Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
3) PHP array_chunk() function
PHP array_chunk() function splits array into chunks. By using
array_chunk() method, you can divide array into many parts.

Syntax

array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

print_r(array_chunk($salary,2));
?>
4) PHP count() function
 PHP count() function counts all elements in an array.

Syntax
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example

<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
Output: 4
a 5) PHP sort() function
PHP sort() function sorts all the elements in an
array.
Syntax
sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example
<?php
season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>

Output:
mn spring summer winter
6) PHP array_reverse() function
PHP array_reverse() function returns an
array containing elements in reversed order.

Syntax

array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example

<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
7) PHP array_search() function
PHP array_search() function searches the specified
value in an array. It returns key if search is successful.

Syntax

mixed array_search ( mixed $needle , array $haystack [, bool $strict =


false ] )

Example
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
Output:
2
8) PHP array_intersect() function
PHP array_intersect() function returns the intersection of two
array. In other words, it returns the matching elements of two array.

Syntax

array array_intersect ( array $array1 , array $array2 [, array $... ] )

Example

<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
Traversing an array
 To traverse an array means to access each element
(item) stored in the array so that the data can be
checked or used as part of a process.
 There are several ways to traverse arrays in PHP, and
the one you choose will depend on your data and the
task you're performing.
1. The foreach Construct. ...
2. The Iterator Functions. ...
3. Using a for Loop. ...
4. Calling a Function for Each Array Element. ...
5. Reducing an Array. ...
6. Searching for Values.
The implode() function
The implode() function returns a string from the elements of an array.

Syntax

implode(separator,array)

Parameter Description

separator Optional. Specifies what to put between the array elements.


Default is "" (an empty string)

array Required. The array to join to a string


Example
PHP explode() Function
The explode() function breaks a string into an array.
Syntax
explode(separator,string,limit)

Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to
return.Possible values:
•Greater than 0 - Returns an array with a maximum of limit
element(s)
•Less than 0 - Returns an array except for the last -limit
elements()
•0 - Returns an array with one element
Example
Example
array_flip() function
 This function is used to flip the array with the
keys and values.
 It takes one parameter that is an array.
 The returned array will contain the flipped
elements.
 The values will be the keys, and the keys will
be the values.
 This function was introduced in PHP 4.0.

Syntax

array array_flip ( array $array )


EXAMPLE 1
<?php

$a = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);


print_r(array_flip($a));

?>
EXAMPLE 2
<?php
$fruits= array('oranges', 'apples', 'banana');

$flipped= array_flip($fruits);

print_r($flipped);
?>
EXAMPLE 3

<?php
function Flip($array)
{
$result = array_flip($array);
return($result);
}
$array = array("amitabh" => "jaya", "raj" => "nargis", "akshay" => "katrina",
"aamir" => "juhi");
print_r(Flip($array));
?>
PHP Functions
 PHP function is a piece of code
that can be reused many times.
 It can take input as argument list
and return value.
 User define and system define
function is types of function
 There are thousands of built-in
functions in PHP.
PHP Functions

A function will be executed by a call to the


function.

> Give the function a name that reflects what the


function does
< The function name can start with a letter or
underscore )not a number)
Advantage of PHP Functions

 Code Reusability: PHP functions are defined only


once and can be invoked many times, like in
other programming languages.
 Less Code: It saves a lot of code because you
don't need to write the logic many times. By the
use of function, you can write the logic only once
and reuse it.
 Easy to understand: PHP functions separate the
programming logic. So it is easier to understand
the flow of the application because every logic is
divided in the form of functions.
PHP User-defined Functions

 We can declare and call user-defined functions easily.


 The syntax to declare user-defined functions.

Syntax:

function functionname()
{
//code to be executed
}

Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.
PHP Functions calling
<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello(); //calling function
?>

Output:
Hello PHP Function
PHP Functions - Parameters
PHP Functions - Parameters
example to pass single argument in PHP function.
<?php
function sayHello($name)
{
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
PHP Functions - Parameters
<?php
function sayHello($name,$age)
{
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
PHP Call By Reference
 Value passed to the function doesn't modify
the actual value by default (call by value).
 But we can do so by passing value as a
reference.
 By default, value passed to the function is call
by value.
 To pass value as a reference, you need to use
ampersand (&) symbol before the argument
name.
Example
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
PHP Function: Default Argument Value

<?php
function sayHello($name="Sonoo")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Variable function
 If name of a variable has parentheses (with or without
parameters in it) in front of it, PHP parser tries to find
a function whose name corresponds to value of the
variable and executes it.
 Such a function is called variable function. This
feature is useful in implementing callbacks, function
tables etc.
 Variable functions can not be built eith language
constructs such as include, require, echo etc. One can
find a workaround though, using function wrappers.
<?php
function add($x, $y)
{
echo $x+$y;
}
$var="add";
$var(10,20);
?>
PHP Anonymous functions
 Anonymous function is a function without any
user defined name.
 Such a function is also called closure or
lambda function. Sometimes, you may want a
function for one time use.
 Closure is an anonymous function which
closes over the environment in which it is
defined.
 You need to specify use keyword in it.Most
common use of anonymous function to create
an inline callback function.
Syntax

$var=function ($arg1, $arg2) { return $val; };


•There is no function name between the function keyword and the
opening parenthesis.
•There is a semicolon after the function definition because

anonymous function definitions are expressions


•Function is assigned to a variable, and called later using the

variable’s name.
•When passed to another function that can then call it later, it is

known as a callback.
•Return it from within an outer function so that it can access the

outer function’s variables. This is known as a closure.


PHP String Function
1)strlen()
- The PHP strlen() function returns the length of a string.
<?php
echo strlen("Hello world!"); // outputs 12
?>

2) str_word_count()
-The PHP str_word_count() function counts the number of words in a
string.
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
PHP String Function
3) strrev() -
The PHP strrev() function reverses a string.
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
4) strpos()
The PHP strpos() function searches for a specific text within a
string. If a match is found, the function returns the character position of the
first match. If no match is found, it will return FALSE.
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
PHP String Function
5) str_replace()

The PHP str_replace() function replaces some characters with


some other characters in a string.
<?php
echo str_replace("world", "Dolly", "Hello world!");
// outputs Hello Dolly!
?>
6) PHP strtolower() function
The strtolower() function returns string in
lowercase letter.

Syntax
string strtolower ( string $string
)

Example
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
7) PHP strtoupper() function
The strtoupper() function returns string in uppercase letter.

Syntax
string strtoupper ( string $string )

Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
8) PHP ucwords() function
The ucwords() function returns string converting first character
of each word into uppercase.

Syntax
string ucwords ( string $str )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
PHP string strcmp() Function
 String comparison is one of the most common
tasks in programming and development.
 strcmp() is a string comparison function in PHP.
 It is a built-in function of PHP, which is case
sensitive, means it treats capital and the small
case separately.
 It is used to compare two strings from each
other.
 This function compares two strings and tells
whether a string is greater, less, or equal to
another string.
 strcmp() function is binary safe string
comparison.
Syntax:
strcmp($str1, $str2);

 strcmp() function accepts two strings


parameter, which is mandatory to pass in the
function body.
 Both parameters are mandatory to pass in
strcmp() function().
 $str1 - It is the first parameter of strcmp()
function that is used in the comparison.
 $str2 - It is the second parameter of strcmp()
function to be used in the comparison.
Value return by strcmp()
This function returns integer value randomly based
on the comparison.
Return 0 - It returns 0 if both strings are equal, i.e., $str1 = $str2
Return < 0 - It returns negative value if string1 is less than
string2, i.e., $str1 < $str2
Return >0 - It returns positive value if string1 is greater than
string 2, i.e., $str1 > $str2
PHP Imagecreate( ) Function

 Image create ( ) function is another inbuilt PHP function


mainly used to create a new image.
 The function returns the given image in a specific size.
We need to define the width and height of the required
image.

Syntax
In PHP, imagecreate( ) function follows the following
syntax.

Imagecreate( $width, $height )


<html lang="en">
<head>
<title>PHP</title>
</head>
<body>
<?Php
// to define the size of the image
$image= imagecreate( 400,200);
// to define the background color of the image
$background-color = imagecolorallocate($image,0, 155, 2);
// to define the text color of the image
$text-color = imagecolorallocate($image,255, 255, 255);
// These function will define the character to be displayed on the screen
Imagestring($image,13,151,121,"this is text 1", $text-color);
Imagestring($image,4,151,101,"this is text 2", $text-color);
Imagestring($image,10,151,81," this is text 3", $text-color);
Imagestring($image,13,151,61," this is text 4", $text-color);
Header("Content - Type: image/png");
Imagepng($image);
Imagedestroy($image);
?>
</body>
</html>
 Image with text

use imagettftext().

 Scaling image
use imagescale() function
Creation of PDF Document
 FPDF is a PHP class which allows generating
PDF
 FPDF has following features
 Choice of measure unit, page format and margins
 Page header and footer management
 Automatic page break
 Automatic line break and text justification
 Image support(JPEG,PNG and GIF)
 Color and links
 TrueType,Type1 and encoding support
 Page compression.
 FPDF is free and downloaded from hhtps://www.fpdf.org)
<?php
require(‘fpdf.php’);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont(‘Arial’,’B’,16);
$pdf->Cell(80,10,’Prof.Patil A.D’);
$pdf->Output(‘my_file.pdf’,’I’);
?>
PHP with OOP
1) Object-oriented programming (OOP)
2)classes and objects are important.
3) OOP models complex things as reproducible,
4) simple structures
5) Reusable,
6) OOP objects can be used across programs
7) Allows for class-specific behavior through polymorphism
8) Easier to debug, classes often contain all applicable information
to them
9)Secure, protects information through encapsulation
PHP - What are Classes and Objects?
1) Classes and objects are the two main aspects of object-
oriented programming.
2) Define a Class

A class is defined by using the class keyword, followed by


the name of the class and a pair of curly braces ({}). All its
properties and methods go inside the braces:
3) Syntax
<?php
class Fruit
{
// code goes here...
}
?>
PHP - What are Classes and Objects?
Example
<?php
class Fruit
{
// Properties
public $name;
public $color;
// Methods
function set_name($name)
{
$this->name = $name;
}
function get_name()
{
return $this->name;
}
}
?>
PHP - What are Classes and Objects?
Define Objects
-Classes are nothing without objects!
-Objects are instances of classes
- We can create multiple objects from a class.
-Objects of a class is created using the new
keyword.
Example
In the example below, $apple and $banana are instances of the class Fruit

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();

?>
PHP - The __construct Function
1) A constructor allows you to initialize an
object's properties upon creation of the object.
2) you create a constructor using __construct()
function,
3) PHP will automatically call this function when
you create an object from a class.
4) Notice that the construct function starts with
two underscores (__)!
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name)
{
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>
PHP - The __destruct Function
1) A destructor is called when the object is
destructed or the script is stopped or exited.
2)you create a destructor using __destruct()
function,
3) PHP will automatically call this function at the
end of the script.
4) Notice that the destruct function starts with two
underscores (__)!
Example
<?php
class Fruit {
public $name;
public $color;

function __construct($name)
{
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>
PHP - What is Inheritance?
1) When a class derives from another class.
2)The child (sub) class will inherit all the public
and protected properties and methods from the
parent class.
3)In addition, it can have its own properties and
methods.
4)The old class is the base class,also called as
parent class or super class
4) An inherited class is defined by using the
extends keyword.
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
Method or function Overloading
 Function overloading or method overloading is the
ability to create multiple functions of the same name
with different implementations depending on the type
of their arguments.
<?php
class Base
{
function show()
{
echo “Display base<br>”
}
}
Class derived extends Base
{
function show()
{
echo “Display Derived<br>”
}
$boj = new devived();
$boj->show();
?>

Both the classes define the same method show(),but


when we inherited ,the derived version of show()
override the base version of show().
When we call show()method it always call the derived
show()method
To call base method we can use parent::method()
Cloning object
 Object cloning is the process in PHP to create a
copy of an object.
 An object copy is created by using the clone
keyword
 An object’s __clone() method cannot be called
directly

Syntax

$copy_object_name= clone $object_to_be_copied


<?php
class MyClass {
public $amount;
public function __clone() {
$value = $this->amount;
unset($this->amount); // Unset breaks references
$this->amount = $value;
}
}

// Create an object with a reference


$value = 5;
$obj = new MyClass();
$obj->amount = &$value;

// Clone the object


$copy = clone $obj;

// Change the value in the original object


$obj->amount = 6;

// The copy is not changed


print_r($copy);
?>
Introspection
 Introspection is the ability of a program to
examine an object's characteristics, such as
its name, parent class (if any), properties, and
methods.
 With introspection allows us
 Obtain the name of the class to which an
object belongs as well as its member
properties and methods.
 Write generic debuggers, serializers,
profiles.
Introspection
1) Examining Classes
• To examining the classes the introspective functions provided by PHP
A. class_exists
• This function is used to determine whether a class exists.
• Its takes a string and return a Boolean value.

Syntax:
$yes_no=class_exists(classname);

<?php
class cwipedia
{
//decl
}
if(class_exists('cwipedia'))
{ $ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{ echo "Not exist";
}
?>
2) get_class_methods()
This function return an array of class methods
name

Syntax:
$method =get_class_methods(classname);

<? Php
class myclass
{
function myclass() { }
function myfun1() { }
}
$my_class=new myclass();
$class_methods =get_class_methods(‘myclass’);
print_r($class_methods)
?> Output:
Array([0]=>myclass [1] => myfun)
3)get_class_vars()
• This function return an array of defaults properties of the class.
• It return an associative array with property’s name value pairs

Syntax
$properties = get_class_vars(classname)

<? Php
class myclass Out Put
{
Array(size=2)’v1’=>null ‘v2’=> int 100
var $v1;
var $v2=100;
}
$my_class = new myclass();
$class_vars= get_class_vars(‘myclass’);
var_ump($class_vars);
?>
4) get_parent_class()
 Parameterize function accept either an object or
class name as parameter.
 It return the name of the parent class
 Or false if there is no parent class

Syntax:
$superclass=get_parent_class(classname)
Examining an object
Serialization in PHP:
 Serialization is a technique used by programmers
to preserve their working data in a format that
can later be restored to its previous form.
 Serializing an object means converting it to a byte
stream representation that can be stored in a file.
 Serialization in PHP is mostly automatic, it
requires little extra work from you, beyond calling
the
 serialize()
 unserialize() functions.
serialize():
 The serialize() converts a storable representation of a
value.
 The serialize() function accepts a single parameter
which is the data we want to serialize and returns a
serialized string
 A serialize data means a sequence of bits so that it can
be stored in a f il e, a memory buffer, or transmitted
across a network connection link.
 It is useful for storing or passing PHP values around
without losing their type and structure.

Syntax: serialize(value);
unserialize():

unserialize():
unserialize() can use string to recreate the
original variable values i.e. converts actual data from
serialized data.

Syntax:
unserialize(string);
Introduction
 PHP becoming standard in the world of web
programming
 Because of simplicity, performance , reliability ,
flexibility & Speed.
 Form are essential parts in web development.
 Form are used to get input from user and
submit it into the web server for processing.
 Form are used to communicate between users
and server.
Process of form handling
GET method
 The GET method is used to submit the HTML
form data.
 This data is collected by the predef ined $_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.
PHP Forms - $_GET Function
 When using method="get" in HTML forms, all
variable names and values are displayed in the
URL.
 This method should not be used when sending
passwords or other sensitive information!
 However, because the variables are displayed in
the URL, it is possible to bookmark the page. This
can be useful in some cases.
 The get method is not suitable for large variable
values; the value cannot exceed 1024 chars.
Some other notes on GET requests:

1) GET requests can be cached


2) GET requests remain in the browser history
3) GET requests can be bookmarked
4) GET requests should never be used when
dealing with sensitive data
5) GET requests have length restrictions
6) GET requests are only used to request data
(not modify)
PHP Forms - $_POST Function
 The built-in $_POST function is used to collect
values from a form sent with method="post".
 Information sent from a form with the POST
method is invisible to others and has no limits
on the amount of information to send.
 Note: However, there is an 8 Mb max size for
the POST method, by default (can be changed
by setting the post_max_size in the php.ini file).
Some other notes on POST requests:

1) POST requests are never cached


2) POST requests do not remain in the browser
history
3) POST requests cannot be bookmarked
4) POST requests have no restrictions on data
length
Get vs. Post
Forms And its Elements

13-Feb-25
What are forms?
 <form> is just another kind of HTML tag
 HTML forms are used to create (rather primitive) GUIs on
Web pages
1. Usually the purpose is to ask the user for information
2. The information is then sent back to the server
 A form is an area that can contain form elements
The syntax is: <form parameters> ...form elements...
</form>
 Form elements include: buttons, checkboxes, text fields
, radio buttons, drop-down menus, etc
 A form usually contains a Submit button to send the
information in he form elements to the server

177
The <form> tag
The <form arguments> ... </form> tag encloses form elements
(and probably other HTML as well)
The arguments to form tell what to do with the user input
action="url" (required)
Specifies where to send the data when the Submit button is clicked
method="get" (default)
Form data is sent as a URL with ?form_data info appended to the end
Can be used only if data is all ASCII and not more than 100 characters
method="post"
Form data is sent in the body of the URL request
Cannot be bookmarked by most browsers
target="target"
Tells where to open the page sent as a result of the request
target= _blank means open in a new window
178
target= _top means use the same window
The <input> tag
Most, but not all, form elements use the input tag, with a
type="..." argument to tell which kind of element it is
type can be text, checkbox, radio, password, hidden, submit, reset,
button, file, or image
Other common input tag arguments include:
name: the name of the element
value: the “value” of the element; used in different ways for different
values of type
readonly: the value cannot be changed
disabled: the user can’t do anything with this element
Other arguments are defined for the input tag but have meaning only
for certain values of type
179
Text input
A text field:
<input type="text" name="textfield" value="with an initial value">

A multi-line text field


<textarea name="textarea" cols="24" rows="2">Hello</textarea>

A password field:
<input type="password" name="textfield3" value="secret">

• Note that two of these use the input tag, but one uses textarea
180
Buttons
A submit button:
<input type="submit" name="Submit" value="Submit">
A reset button:
<input type="reset" name="Submit2" value="Reset">
A plain button:
<input type="button" name="Submit3" value="Push Me">
submit: send data

reset: restore all form elements to


their initial state
button: take some action as specified
by JavaScript
• Note that the type is input, not “button”
181
Checkboxes
A checkbox:
<input type="checkbox" name="checkbox”
value="checkbox" checked>

type: "checkbox"
name: used to reference this form element from PHP
value: value to be returned when element is checked
Note that there is no text associated with the
checkbox—you have to supply text in the surrounding
HTML

182
Radio buttons
Radio buttons:<br>
<input type="radio" name="radiobutton" value="myValue1">
male<br>
<input type="radio" name="radiobutton" value="myValue2" checked>
female

If two or more radio buttons have the same name, the user can
only select one of them at a time
This is how you make a radio button “group”
If you ask for the value of that name, you will get the value
specified for the selected radio button
As
183 with checkboxes, radio buttons do not contain any text
Drop-down menu or list
A menu or list:
<select name="select">
<option value="red">red</option>
<option value="green">green</option>
<option value="BLUE">blue</option>
</select>

Additional arguments:
size: the number of items visible in the list (default is "1")
multiple: if set to "true", any number of items may be selected
(default is "false")

184
Hidden fields
<input type="hidden" name="hiddenField" value="nyah">
&lt;-- right there, don't you see it?

What good is this?


All input fields are sent back to the server, including hidden fields
This is a way to include information that the user doesn’t need to see (or
that you don’t want her to see)
The value of a hidden field can be set programmatically (by JavaScript)
before the form is submitted

185
A complete example
<html>
<head>
<title>Get Identity</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<p><b>Who are you?</b></p>
<form method="post" action="">
<p>Name:
<input type="text" name="textfield">
</p>
<p>Gender:
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female</p>
</form>
</body>
</html>
186
By inserting value in a form we can check that inserted
value is even or odd.

<html>
<body>
<form method="post">
Enter a number:
<input type="number" name="number">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
if($_POST)
{
$number = $_POST['number'];
if(($number % 2) == 0)
{
echo "$number is an Even number";
}
else
{
echo "$number is Odd number";
}
}
?>
Prime Number using Form in PHP
<form method="post">
Enter a Number: <input type="text" name="input"><br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if($_POST)
{
$input=$_POST['input'];
for ($i = 2; $i <= $input-1; $i++)
{
if ($input % $i == 0)
{
$value= True;
}
}
if (isset($value) && $value)
{
echo 'The Number '. $input . ' is not prime';
} else
{
echo 'The Number '. $input . ' is prime';
}
}
?>
What is a Cookie?
 PHP cookie is a small piece of information which
is stored at client browser.
 It is used to recognize the user.
 Cookie is created at server side and saved to
client browser.
 Each time when client sends request to the
server, cookie is embedded with request.
 Such way, cookie can be received at the server
side.
Each cookie be used to store up to 4kB of data.
 A maximum of 20 cookies can be stored on a
user’s PC per domain.
Set a cookie
setcookie(name [,value [,expire [,path [,domain [,secure]]]]])

name = cookie name


value = data to store (string)
expire = UNIX timestamp when the cookie expires. Default is that cookie
expires when browser is closed.
path = Path on the server within and below which the cookie is available
on.
domain = Domain at which the cookie is available for.
secure = If cookie should be sent over HTTPS connection only. Default
false.
Set a cookie - examples
setcookie(‘name’,’Robert’)
This command will set the cookie called name
on the user’s PC containing the data Robert. It
will be available to all pages in the same
directory or subdirectory of the page that set it
(the default path and domain). It will expire and
be deleted when the browser is closed (default
expire).
Set a cookie - examples
setcookie(‘age’,’20’,time()+60*60*24*30)
This command will set the cookie called age on
the user’s PC containing the data 20. It will be
available to all pages in the same directory or
subdirectory of the page that set it (the default
path and domain). It will expire and be deleted
after 30 days.
Set a cookie - examples
setcookie(‘gender’,’male’,0,’/’)
This command will set the cookie called gender
on the user’s PC containing the data male. It
will be available within the entire domain that
set it. It will expire and be deleted when the
browser is closed.
Read cookie data
All cookie data is available through the
superglobal $_COOKIE:
$variable = $_COOKIE[‘cookie_name’]

or
$variable = $HTTP_COOKIE_VARS[‘cookie_name’];

e.g.
$age = $_COOKIE[‘age’]
Storing an array..
Only strings can be stored in Cookie files.
To store an array in a cookie, convert it to a string
by using the serialize() PHP function.
The array can be reconstructed using the
unserialize() function once it had been read
back in.
Remember cookie size is limited!
Delete a cookie
To remove a cookie, simply overwrite the cookie
with a new one with an expiry time in the past…

setcookie(‘cookie_name’,’’,time()-6000)

Note that theoretically any number taken away


from the time() function should do, but due to
variations in local computer times, it is advisable
to use a day or two.
Cookie Vs. Session

Cookie Session

•Cookies are client-side files that contain user •Sessions are server-side files which contain user
information information

•Cookie ends depending on the lifetime you set for it •A session ends when a user closes his browser

•You don't need to start cookie as it is stored in your local •In PHP, before using $_SESSION, you have to write
machine session_start(); Likewise for other languages

•The official maximum cookie size is 4KB •Within-session you can store as much data as you like.
The only limits you can reach is the maximum memory a
script can consume at one time, which is 128MB by
default

•A cookie is not dependent on Session •A session is dependent on Cookie

•There is no function named unsetcookie() •Session_destroy(); is used to destroy all registered data
or to unset some

You might also like