WBP Notes Info
WBP Notes Info
What is PHP?
PHP is a general-purpose scripting language especially suited to web development.
● PHP stands for PHP hypertext preprocessor
● PHP is a server side programming language that is embedded in HTML.
● PHP allows web developers to create dynamic contents that interact with database,
session management etc.
● It is integrated with popular databases like MySQL, postgreSQL, Oracle etc.
● PHP is basically used for developing web apps
● PHP is open source
Why PHP?
t
● PHP runs on different OS platforms like
o Windows (WAMP)
ne
o Linux (LAMP)
o MAC OS (MAMP)
● PHP is an interpreted language.
● PHP is compatible with almost all servers but the most used server is apache.
● PHP is open source so it is free to download and use
la
● PHP is easy to use and widely used.
Characteristics of PHP
● Simplicity
P
● Efficiency
● Security
● Flexibility
● Familiarity
fo
● Wikipedia
● WordPress
20+ million other domains are using PHP
History of PHP
Versions:
● PHP /FI 1.0 released in 1995
● PHP /FI 2.0 released in 1997
● PHP 3.0 released in 1998
● PHP 4.0 released in 2000
● PHP 5.0 released in 2004
● PHP 5.3 released in 2009
● PHP 7.0 released in 2014
t
sophisticated structure for event of web applications.
● It helps in managing code easily.
ne
● It has powerful library support to use various function modules for data
representation.
● PHP’s built-in database connection modules help in connecting database easily reduce
trouble and time for development of web applications and content based sites.
● Popularity of PHP gave rise to various communities of developers, a fraction of which
la
may be potential candidates for hire.
● Flexibility makes PHP ready to effectively combine with many other programming
languages in order that the software package could use foremost effective technology
for every particular feature.
P
Syntax of PHP:
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
fo
<?php
// PHP code goes here
?>
<?php
echo "Hello, World!";
In
?>
echo is a command used in PHP to display anything on screen.
Comments:
• // this is single line comment
• # this is also single line comment
• /* this is multi line comment,
• can spread over thousands of lines */
t
the assignment operator ‘=’.
● One must keep in mind that variable names in PHP names must start with a letter or
ne
underscore and no numbers.
● PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values. The same
happens while conversion. No variables are declared before they are used. It
automatically converts types from one type to another whenever required.
la
● PHP variables are case-sensitive, i.e. $sum and $SUM are treated differently.
Constants
● A constant is an identifier (name) for a simple value. The value cannot be changed
P
during the script.
● A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Syntax:
fo
example:
<!DOCTYPE html>
In
<html>
<body>
<?php
// case-sensitive constant name
define("GREETING", "Welcome to Softanic!");
echo GREETING;
?>
</body>
</html>
Variable Scopes
Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the
scope of a variable is the portion of the program within which it is visible or can be accessed.
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 3
Depending on the scopes, PHP has three variable scopes:
Local variables: The variables declared within a function are called local variables to that
function and have its scope only in that particular function. In simple words, it cannot be
accessed outside that function. Any declaration of a variable outside the function with the
same name as that of the one within the function is a completely different variable. We will
learn about functions in detail in later articles. For now, consider a function as a block of
statements.
Global variables: The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get access within a function
we need to use the “global” keyword before the variable to refer to the global variable.
Static variable: It is the characteristic of PHP to delete the variable, ones it completes its
execution and the memory is freed. But sometimes we need to store the variables even after
the completion of function execution. To do this we use static keyword and the variables are
t
then called as static variables. PHP associates a data type depending on the value for the
variable.
ne
<?php
function static_var()
{
// static variable
static $num = 5;
$sum = 2;
la
$sum++;
$num++;
P
echo $num, "\n";
echo $sum, "\n";
}
// first function call
static_var();
fo
?>
Output:
In
6
3
7
3
Datatypes
● Data types specify the size and type of values that can be stored.
● Variable does not need to be declared ITS DATA TYPE adding a value to it.
● PHP is a Loosely Typed Language so here no need to define data type
● To check only data type use gettype( ) function.
● To check value, data type and size use var_dump( ) function.
t
Operators are symbols that tell the PHP processor to perform certain actions. For example,
the addition (+) symbol is an operator that tells PHP to add two variables or values, while the
ne
greater-than (>) symbol is an operator that tells PHP to compare two values.
The following lists describe the different operators used in PHP.
Example:
<!DOCTYPE html>
In
<html lang="en">
<head>
<title>PHP Arithmetic Operators</title>
</head>
<body>
<?php
$x = 10;
$y = 4;
echo($x + $y);
echo "<br>";
echo($x - $y);
echo "<br>";
echo($x * $y);
Output:
14
6
40
t
2.5
2
ne
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
la
Operator Description Example Is The Same As
= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
P
-= Subtract and assign $x -= $y $x = $x - $y
*= Multiply and assign $x *= $y $x = $x * $y
/= Divide and assign quotient $x /= $y $x = $x / $y
fo
Example:
<!DOCTYPE html>
<?php
$x = 10;
echo $x;
echo "<br>";
$x = 20;
$x += 30;
echo $x;
t
echo "<br>";
$x = 50;
ne
$x -= 20;
echo $x;
echo "<br>";
$x = 5;
$x *= 25;
echo $x;
la
echo "<br>";
$x = 50;
$x /= 10;
P
echo $x;
echo "<br>";
$x = 100;
$x %= 15;
fo
echo $x;
?>
</body>
</html>
In
Output:
10
50
30
125
5
10
t
$y
ne
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP Comparison Operators</title>
</head>
la
<body>
<?php
$x = 25;
P
$y = 35;
$z = "25";
var_dump($x == $z);
echo "<br>";
fo
echo "<br>";
var_dump($x < $y);
echo "<br>";
var_dump($x > $y);
echo "<br>";
var_dump($x <= $y);
echo "<br>";
var_dump($x >= $y);
?>
</body>
</html>
Output:
t
Operator Name Effect
++$x Pre-increment Increments $x by one, then returns $x
ne
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
la
P
Example:
<!DOCTYPE html>
<html lang="en">
<head>
fo
echo ++$x;
echo "<br>";
echo $x;
echo "<hr>";
$x = 10;
echo $x++;
echo "<br>";
echo $x;
echo "<hr>";
$x = 10;
echo --$x;
echo "<br>";
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 9
echo $x;
echo "<hr>";
$x = 10;
echo $x--;
echo "<br>";
echo $x;
?>
</body>
</html>
Output:
t
11
11
ne
10
11
9
9
la
10
9
P
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP Logical Operators</title>
</head>
<body>
<?php
</body>
</html>
Output:
2014 is not a leap year.
t
PHP String Operators
ne
There are two operators which are specifically designed for strings.
Operator Description Example Result
<body>
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
In
echo "<br>";
$x .= $y;
echo $x; // Outputs: Hello World!
?>
</body>
</html>
Output:
Hello World!
Hello World!
t
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
ne
!== Non-identi $x !== $y True if $x is not identical to $y
ty la
P
fo
<html lang="en">
<head>
<title>PHP Array Operators</title>
</head>
<body>
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
echo "<hr>";
var_dump($x == $y);
echo "<br>";
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 12
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x <> $y);
echo "<br>";
var_dump($x !== $y);
?>
</body>
</html>
Output:
array(6) { ["a"]=> string(3) "Red" ["b"]=> string(5) "Green" ["c"]=> string(4) "Blue"
t
["u"]=> string(6) "Yellow" ["v"]=> string(6) "Orange" ["w"]=> string(4) "Pink" }
bool(false)
ne
bool(false)
bool(true)
bool(true)
bool(true)
la
P
fo
In
if Statement
The if statement executes some code if one condition is true.
Syntax:
t
if (condition) {
code to be executed if condition is true;
ne
}
Example:
<!DOCTYPE html>
<html>
la
<body>
<?php
$t = date("H");
if ($t < "20") {
P
echo "Have a good day!";
}
?>
</body>
fo
</html>
Output:
Have a good day!
In
if...else Statement
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example:
<!DOCTYPE html>
<html>
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 14
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>
Output:
t
Have a good day!
if...elseif...else Statement
ne
The if...elseif...else statement executes different codes for more than two conditions.
Syntax:
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
la
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
P
}
Example:
<!DOCTYPE html>
<html>
fo
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
In
Output:
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 15
The hour (of the server) is 10, and will give the following message:
Have a good day!
switch Statement
The switch statement is used to perform different actions based on different conditions.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
t
break;
case label3:
ne
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
la
}
Example:
<!DOCTYPE html>
P
<html>
<body>
<?php
fo
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
In
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 16
</html>
Output:
Your favorite color is red!
break Statement
Sometimes a situation arises where we want to exit from a loop immediately without waiting
to get back to the conditional statement.
The keyword break ends execution of the current for, foreach, while, do
while or switch structure. When the keyword break executed inside a loop the control
automatically passes to the first statement outside the loop. A break is usually associated with
the if.
Example:
t
<?php
$array1=array(100, 1100, 200, 400, 900);
ne
$x1=0;
$sum=0
while ($x1<=4)
{
if ($sum>1500)
la
{
break;
}
$sum = $sum+$array1[$x1];
P
$x1=$x1+1;
}
echo $sum;
?>
fo
Output:
1800
continue Statement
In
Sometimes a situation arises where we want to take the control to the beginning of the loop
(for example for, while, do while etc.) skipping the rest statements inside the loop which have
not yet been executed.
The keyword continue allow us to do this. When the keyword continue executed inside a loop
the control automatically passes to the beginning of loop. Continue is usually associated with
the if.
Example:
<?php
$x=1;
echo 'List of odd numbers between 1 to 10 <br />';
while ($x<=10)
{
if (($x % 2)==0)
t
Output:
List of odd numbers between 1 to 10
ne
1
3
5
7
9
la
P
fo
In
while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax:
t
while (condition is true) {
code to be executed;
ne
}
Examples:
<?php
$x = 1;
la
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
P
?>
Output:
The number is: 1
fo
Do while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax:
do {
code to be executed;
} while (condition is true);
Examples:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax:
t
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
ne
}
Parameters:
● init counter: Initialize the loop counter value
● test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the
la
loop continues. If it evaluates to FALSE, the loop ends.
● increment counter: Increases the loop counter value
Example:
P
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
fo
?>
Output:
The number is: 0
The number is: 1
In
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
t
echo "$value <br>";
}
ne
?>
Output:
red
green
blue
la
yellow
P
fo
In
t
There are basically three types of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index where values are stored
ne
linearly.
Associative Arrays: An array with a string index where instead of linear storage, each value
can be assigned a specific key.
Multidimensional Arrays: An array which contains single or multiple array within it and
can be accessed via multiple indices
la
Indexed or Numeric Arrays
These type of arrays can be used to store any type of elements, but an index is always a
number. By default, the index starts at zero. These arrays can be created in two different ways
P
as shown in the following example:
<?php
Traversing: We can traverse an indexed array using loops in PHP. We can loop through the
t
indexed array in two ways. First by using for loop and secondly by using foreach. You can
refer to PHP | Loops for the syntax and basic use.
<?php
ne
// Creating an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
?>
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every
value can be assigned with a user-defined key of string type.
<?php
t
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
ne
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";
?>
la
Output:
Accessing the elements directly:
zara
P
sara
any
Rani
Ravina
fo
Traversing Associative Arrays: We can traverse associative arrays in a similar way did in
numeric arrays using loops. We can loop through the associative array in two ways. First by
using for loop and secondly by using foreach. You can refer to PHP | Loops for the syntax
and basic use.
Example:
In
<?php
?>
Output:
Looping using foreach:
t
Husband is Zack and Wife is Zara
Husband is Anthony and Wife is Any
Husband is Ram and Wife is Rani
ne
Husband is Salim and Wife is Sara
Husband is Raghav and Wife is Ravina
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a
single element. In other words, we can define multi-dimensional arrays as an array of arrays.
fo
As the name suggests, every element in this array can be an array and they can also hold
other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed
using multiple dimensions.
Example:
In
<?php
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];
?>
t
Output:
ne
Dave Punk email-id is: [email protected]
John Flinch mobile number is: 9875147536
la
Array functions
1. Implode()
PHP implode Function joins elements of an array into a single string. It returns a
P
string containing elements of the array.
Syntax:
implode($delimiter , $array );
fo
PHP implode Function expects two parameters. One parameter is mandatory while the
other is optional. However, it accepts the parameters in either order.
⮚ $delimiter: Delimiter or the separator is an optional parameter and specifies by
what character the array elements will be joined. The default value of delimiter is
In
an empty string.
⮚ $array: $array is an array of strings to implode. It is a mandatory parameter.
Return Value:
PHP implode Function returns a string from the elements of the array separated by the
given delimiter.
Ex.
PHP explode Function is an inbuilt string function of PHP. Explode literally means to
break down. The Function splits or breaks a string into an array of strings. It returns
an array containing exploded sub-strings of the string. Sub-strings form by splitting
the string by given string delimiter.
Syntax
explode($delimiter, $string);
Parameters
PHP Explode Function expects two mandatory parameters and one optional
parameter. The description of the parameters is as follows:
t
⮚ $delimiter: Delimiter or the separator is the mandatory parameter. It specifies
where to break the string from. The function will split the string around the
ne
delimiter.
⮚ $string: Original string on which explode operation is to be performed. It is also a
mandatory parameter.
Return Value
la
PHP Explode Function returns an array containing the sub-strings of the string
exploded. Moreover, the return values also depend upon the limit passed.
<?php
P
$string = "Hi-how-are-you-doing?";
$explodedString = explode('-', $string);
print_r($explodedString);
?>
fo
Output
Array
(
[0] => Hi
[1] => how
In
3. Array_flip()
The PHP array_flip Function is an inbuilt function in PHP which exchanges the keys
with their values in the associative array. It returns an array with the corresponding
keys and values exchanged. However, the values of the existing array should be valid
keys ie. either string or integer. The function throws a warning if the new keys are not
valid.
print_r($flipped);
t
?>
Output:
ne
Array
(
[oranges] => 0
[apples] => 1
[pears] => 2
)
la
4. Array_push()
PHP array_push Function is an inbuilt function in PHP which inserts new elements in
an array. It always inserts elements at the end of the array. The count of the array is
P
also incremented by one. Moreover, multiple elements can be passed in the
array_push function at once.
Syntax:
array_push($array, $val1, $val2, $val3 ….);
Parameters:
fo
We can pass multiple parameters in the PHP array_push Function. It depends on the
number of elements we want to add at once. Let’s consider two types of categories of
elements that can be passed:
⮚ $array: The first parameter is a mandatory array. The PHP array_push Function
In
inserts new elements in this input array. An empty array can also be passed as the
first parameter.
⮚ $elementList: The second parameter is the comma-separated element list we want
to add to array in PHP.
Return Value:
The function returns the modified array with all the elements inserted at the end.
Note: The PHP array_push method always adds a new numeric key in the original
array even if the array has string keys.
Example:
t
[0] => 1
[1] => Concatly
)
ne
*/
array_push($testArray, array('John', 'Doe'));
print_r($testArray);
/*
Array
(
la
[0] => 1
[1] => Concatly
[2] => Array
(
P
[0] => John
[1] => Doe
)
)
*/
fo
?>
5. array_pop()
PHP array_pop Function is an inbuilt function in PHP which removes the last element
from an array. It returns the last value of the array. Also, it decrements the size of the
In
If you don’t pass any parameter, PHP array_pop Function throws a Warning.
However, it does not throw any warning/notice on passing an empty array.
Return Value:
The function returns the last element of the array. The returned element is removed
from the array. If the array is empty, then it returns NULL.
Ex.
Array
(
[0] => orange
[1] => banana
[2] => apple
)
t
6. count() / sizeof()
The count Function in PHP is one of the most used inbuilt functions. It returns the
ne
count of elements in an array in PHP. In this article, we will discuss the PHP count
Function.
7. sort()
PHP sort is an inbuilt function in PHP. It sorts an array in ascending order i.e, from
In
smaller to bigger element. Also, it makes the changes in the original array itself.
Note: The function assigns new keys to the elements in the array. It will remove any
existing keys rather than re-ordering.
Example:
<?php
$array = array(5, 1, 2, 7, 3);
sort($array);
print_r($array);
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 30
/*
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
[4] => 7
)
*/
?>
8. rsort()
PHP rsort is an inbuilt function in PHP. It sorts an array in descending order i.e, from
bigger to smaller element. Also, it makes the changes in the original array itself.
t
Syntax: boolean rsort($array)
ne
Return Value:
The PHP rsort Function returns true on success and false on failure. However, it
modifies the original input array.
Note: The function assigns new keys to the elements in the array. It will remove any
existing keys rather than re-ordering.
la
Example:
<?php
$array = array(5, 1, 2, 7, 3);
rsort($array);
P
print_r($array);
/*
Array
(
[0] => 7
fo
[1] => 5
[2] => 3
[3] => 2
[4] => 1
)
*/
In
?>
9. asort()
PHP asort is an inbuilt Function in PHP. It sorts arrays in ascending order while
maintaining the relationship between keys and values. The smallest element in the
input array appears first and the largest appears last.
Note: This function is mostly helpful in sorting Associative Arrays because the
because it preserves the relation between keys and values.
Syntax:
bool asort( $array )
Example:
<?php
?>
10. arsort()
PHP arsort is an inbuilt Function in PHP. It sorts arrays in descending order while
t
maintaining the relationship between keys and values. The smallest element in the
input array appears first and the largest appears last.
ne
Note: This function is mostly helpful in sorting Associative Arrays because the
because it preserves the relation between keys and values.
Syntax:
bool arsort( $array )
la
Example:
<?php
$array = array(5, 1, 2, 7, 3);
arsort($array);
print_r($array);
P
//Keys are preserved
/*
Array
(
fo
[3] => 7
[0] => 5
[4] => 3
[2] => 2
[1] => 1
)
In
*/
?>
11. ksort()
PHP ksort is an inbuilt Function in PHP. It sorts arrays in ascending order according
to keys while maintaining the relationship between keys and values. The smallest key
in the input array appears first and the largest appears last.
12. krsort()
PHP krsort is an inbuilt Function in PHP. It sorts arrays in descending order according
to keys while maintaining the relationship between keys and values. The smallest key
t
in the input array appears last and the largest appears first.
ne
Ex.
<?php
)
*/
?>
13. in_array()
In
Syntax:
bool in_array ($needle, $haystack, $strictMode = false)
Parameters:
The PHP in_array Function takes in three parameters. Two parameters are mandatory
and one is optional. Let’s discuss about the parameters below:
Return Value:
The PHP in_array Function returns a boolean value. If the needle is present in the
haystack, then it returns true. Otherwise, it returns false.
Example:
<?php
$haystack = array(5, 0, 6, 21, 63, 24);
var_dump(in_array(6, $haystack));
/* bool(true) */
var_dump(in_array(1, $haystack));
t
/* bool(false) */
?>
ne
14. array_merge()
PHP array_merge Function is an inbuilt Function in PHP which merges two or more arrays.
This function merges elements in two or more arrays into one single array. While merging, it
appends the elements of an array at the end of the previous array.
la
Syntax:
array array_merge($array1, $array2, ……, $arrayn)
Parameters:
The PHP array_merge Function takes in a list of array parameters. You can pass any number
of parameters in the function. However, all the parameters must be arrays.
P
If the input arrays contain the same numeric keys, then the PHP array_merge will append the
keys and not overwrite them. However, if the arrays contain the same string keys then it
overwrites the later value of the keys with the previous one.
Return Value:
fo
The PHP array_merge Function in PHP returns a single array after merging the arrays passed
in the parameters.
Values in the input arrays with numeric keys will be renumbered with incrementing keys
starting from zero in the result array
In
Example:
<?php
$array1 = array(1,3,5);
$array2 = array(2,4,6);
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
/*
OUTPUT
Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 2
[4] => 4
t
ne
la
P
fo
In
A function is a reusable block of statements that performs a specific task. This block
is defined with function keyword and is given a name that starts with an alphabet or
underscore. This function may be called from anywhere within the program any number of
times
● A function is a block of statements that can be used repeatedly in a program.
● A function will not execute automatically when a page loads.
● A function will be executed by a call to the function.
t
User define functions
ne
Function whose definition is defined by user is called as user define function.
A user-defined function declaration starts with the word function:
function functionName() {
code to be executed;
}
la
functionName(); // function call
Rules for function name:
⮚ Function name must start with letter or underscore followed by any number, letter
or underscore( _ )
P
⮚ Function name cannot start with number or any other special symbol
⮚ Function names are not case sensitive.
⮚ NOTE: You must give function name that shows the working of function
Built in Functions
fo
Built in functions are functions who are already provided by PHP. The real power of
php comes from its functions. PHP has more than 1000 functions.
Ex. Echo(), print(), strlen(), print_r()
User define or built in functions may have parameters
In
t
Add5($n);
Echo “After function call = $n”;
ne
// output
// Before function call = 10
// After function call = 15
Functions may or may not return some value. One function can have one or more
return statements but only one statement will be executed at a function call.
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Ex.
<?php
function hello($name, $num=12)
{
echo "$name is $num years old \n";
}
Variable functions
If the 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 the value of the variable and
executes it. Such a function is called a variable function. This feature is useful in
implementing callbacks etc.
<?php
function hello(){
echo "Hello World";
t
}
$var="Hello";
ne
$var();
?>
Anonymous functions
la
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.
P
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
fo
The strlen() is a built-in function in PHP which returns the length of a given string. It
takes a string as a parameter and returns its length. It calculates the length of the string
including all the whitespaces and special characters.
Syntax:
strlen($string);
Parameters: The strlen() function accepts only one parameter $string which is
mandatory. This parameter represents the string whose length is needed to be
returned.
Example 1: The below example demonstrates the use of the strlen() function in PHP.
<?php
t
?>
ne
Output:
13
2. str_word_count()
The str_word_count() function is a built-in function in PHP and is used to return
la
information about words used in a string like total number word in the string,
positions of the words in the string etc.
P
Syntax:
str_word_count ( $string , $returnVal, $chars )
Parameters Used:
fo
⮚ $string:This parameter specifies the string whose words the user intends to
count.This is not an optional parameter.
⮚ $returnVal:The return value of str_word_count() function is specified by the
In
Return Type: The return type of function depends on the parameter $returnVal and
return the values as described above.
<?php
$mystring = "Twinkle twinkl4e little star";
print_r(str_word_count($mystring));
?>
Output:
3. strrev()
Reversing a string is one of the most basic string operations and is used very
t
frequently by developers and programmers. PHP comes with a built-in function to
reverse strings.
ne
The strrev() function is a built-in function in PHP and is used to reverse a string. This
function does not make any change in the original string passed to it as a parameter.
Syntax:
string strrev($inpString)
la
Parameter: This function accepts a single parameter $inpString. This parameter is a
string and it specifies the string which we want to reverse. If a number is passed to it
P
instead of a string, it will also reverse that number.
Return Value: The strrev() function returns the reversed string or the number. It does
not make any change to the original string or number passed in the parameter.
fo
Examples:
4. strops()
This function helps us to find the position of the first occurrence of a string in another
string. This returns an integer value of the position of the first occurrence of the
string. This function is case-sensitive, which means that it treats upper-case and
lower-case characters differently.
Syntax:
t
original_str where the string search_str first occurs.
ne
5. str_replace()
The str_replace() is a built-in function in PHP and is used to replace all the
occurrences of the search string or array of search strings by replacement string or
array of replacement strings in the given string or array respectively.
Syntax:
la
str_replace ( $searchVal, $replaceVal, $subjectVal, $count )
Parameters: This function accepts 4 parameters out of which 3 are mandatory and 1
P
is optional. All of these parameters are described below:
⮚ $searchVal: This parameter can be of both string and array types. This parameter
specifies the string to be searched and replaced.
⮚ $replaceVal: This parameter can be of both string and array types. This parameter
specifies the string with which we want to replace the $searchVal string.
fo
⮚ $subjectVal: This parameter can be of both string and array types. This parameter
specifies the string or array of strings which we want to search for $searchVal and
replace with $replaceVal.
⮚ $count: This parameter is optional and if passed, its value will be set to the total
In
Syntax:
ucfirst($string)
Parameter: The function accepts only one parameter $string which is mandatory.
This parameter represents the string whose first character will be changed to
uppercase.
7. uc_words()
The ucwords() function is a built-in function in PHP and is used to convert the first
character of every word in a string to upper-case.
Syntax:
string ucwords ( $string, $separator )
Parameter: This function accepts two parameters out of which first is compulsory
and second is optional. Both of the parameters are explained below:
⮚ $string: This is the input string of which you want to convert the first character of
every word to uppercase.
t
⮚ $separator: This is an optional parameter. This parameter specifies a character
which will be used as a separator for the words in the input string. For example, if
the separator character is ‘|’ and the input string is “Hello|world” then it means
ne
that the string contains two words “Hello” and “world”.
Return value: This function returns a string with the first character of every word in
uppercase.
8. strtolower()
la
The strtolower() function is used to convert a string into lowercase. This function
takes a string as parameter and converts all the uppercase english alphabets present in
the string to lowercase. All other numeric characters or special characters in the string
remains unchanged.
P
Syntax:
lower case.
Return value: This function returns a string in which all the alphabets are lower case.
In
9. strtoupper()
The strtoupper() function is used to convert a string into uppercase. This function
takes a string as a parameter and converts all the lowercase english alphabets present
in the string to uppercase. All other numeric characters or special characters in the
string remain unchanged.
Syntax:
Syntax:
strcmp($string1, $string2)
Parameters: This function accepts two parameters which are described below:
t
⮚ $string1 (mandatory): This parameter refers to the first string to be used in the
comparison
ne
⮚ $string2 (mandatory): This parameter refers to the second string to be used in the
comparison.
Return Values: The function returns a random integer value depending on the
condition of match, which is given by:
Returns 0 if the strings are equal.
la
Returns a negative value (<0), if $string2 is greater than $string1.
Returns a positive value (>0) if $string1 is greater than $string2.
P
fo
In
imagecreate() Function
The imagecreate() function is an inbuilt function in PHP which is used to create a new image.
This function returns the blank image of given size. In general imagecreatetruecolor()
function is used instead of imagecreate() function because imagecreatetruecolor() function
creates high quality images.
Syntax:
imagecreate( $width, $height )
Parameters: This function accepts two parameters as mentioned above and described below:
⮚ $width: It is mandatory parameter which is used to specify the image width.
⮚ $height: It is mandatory parameter which is used to specify the image height.
t
Return Value: This function returns an image resource identifier on success, FALSE on
ne
errors.
imagecolorallocate() Function
The imagecolorallocate() function is an inbuilt function in PHP which is used to set the color
in an image. This function returns a color which is given in RGB format.
Syntax:
la
int imagecolorallocate ( $image, $red, $green, $blue )
Parameters: This function accepts four parameters as mentioned above and described below:
⮚ $image: It is returned by one of the image creation functions, such as
P
Return Value: This function returns a color identifier on success or FALSE if the color
allocation failed.
imagestring() Function
In
The imagestring() function is an inbuilt function in PHP which is used to draw a string.
Syntax:
bool imagestring( $image, $font, $x, $y, $string, $color )
Parameters: This function accepts six parameters as mentioned above and described below:
⮚ $image: The imagecreate () function is used to create a blank image in a given
size.
⮚ $font: This parameter is used to set the font size. Inbuilt font in latin2 encoding
can be 1, 2, 3, 4, 5
⮚ $x: This parameter is used to hold the x-coordinate of the upper left corner.
imagerectangle()
The imagerectangle() function is an inbuilt function in PHP which is used to draw the
rectangle.
Syntax:
t
bool imagerectangle( $image, $x1, $y1, $x2, $y2, $color )
Parameters: This function accepts six parameters as mentioned above and described below:
ne
⮚ $image: It is returned by one of the image creation functions, such as
imagecreatetruecolor(). It is used to create size of image.
⮚ $x1: This parameter is used to set the upper left x-coordinate.
⮚ $y1: This parameter is used to set the upper left y-coordinate.
⮚ $x2: This parameter is used to set the bottom right x-coordinate.
la
⮚ $y2: This parameter is used to set the bottom right y-coordinate.
⮚ $color: A color identifier created with imagecolorallocate().
imagepolygon() Function
fo
The imagepolygon() function is an inbuilt function in PHP which is used to draw a polygon.
This function returns TRUE on success and returns FALSE otherwise.
Syntax:
bool imagepolygon( $image, $points, $num_points, $color )
In
Parameters: This function accepts four parameters as mentioned above and described below:
⮚ $image: The imagecreatetruecolor() function is used to create a blank image in a
given size.
⮚ $points: This parameter is used to hold the consecutive vertices of polygon.
⮚ $num_points: This parameter contains total number of vertices in a polygon. It must
be greater then 3, because minimum three vertices required to create a polygon.
⮚ $color: This variable contains the filled color identifier. A color identifier created with
imagecolorallocate() function.
Example:
<?php
t
250, 250 // Point 3 (x, y)
);
ne
// Set the background color of image
$background_color = imagecolorallocate($image, 0, 153, 0);
imagepng($image);
?>
$pdf=new fpdf();
t
▪ unit: pt: point, mm: millimeter (default), cm: centimeter, in: inch
▪ size: A3, A4(default), A5, Letter, Legal or an array containing the width and
ne
the height (expressed in the unit given by unit).
addPage() function
$pdf->addPage(“orientation”,”size”,”rotation”);
la
⮚ Rotation value must be in multiple of 90;
Setfont() function
$pdf->SetFont('Arial','B',16);
P
o B=bold
o I=italic
o U=underline
fo
Cell function
Cell(float w , float h , string txt , mixed border , int ln , string align , boolean fill ,
mixed link)
o W= Width
In
o H= height
o Text is string to print
o Border: 0 – no border / 1- border / L –left / T-top/ R-right/ B-Bottom
o Ln: Indicates where the current position should go after the call. Possible
values are 0: to the right / 1: to the beginning of the next line / 2: below
o Align: L or empty string: left align (default value) / C: center / R: right align
o Fill : 1 - true/ 0 – false
o Link: URL
Output() function
string Output([string dest [, string name]])
⮚ Dest:
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 47
o I: send the file inline to the browser. The PDF viewer is used if available.
(default)
o D: send to the browser and force a file download with the name given by
name.
o F: save to a local file with the name given by name (may include a path).
o S: return the document as a string.
⮚ name
o The name of the file. The default value is doc.pdf.
t
❖ $pdf->Image("info.png", x position, y position, width, height);
We can add images in pdf file using image function
ne
❖ $pdf->Line(float x1, float y1, float x2, float y2)
we can add line using this function
❖ $pdf->SetLineWidth(float width)
We can set custom width of lines using this function
❖ $pdf->SetDrawColor(rgb);
la
We can change color of lines using this function
❖ $pdf->pageNo();
We can get page no of pdf file using this function.
P
fo
In
We can imagine our universe made of different objects like the sun, earth, moon etc.
Similarly we can imagine our car made of different objects like wheels, steering, gear etc.
Same way there is object oriented programming concepts which assume everything as an
object and implement a software using different objects.
Object Oriented Concepts
Before we go in detail, let's define important terms related to Object Oriented Programming.
➔ Class − This is a programmer-defined data type, which includes local functions as
well as local data. You can think of a class as a template for making many instances of
the same kind (or class) of objects.
➔ Object − An individual instance of the data structure defined by a class. You define a
t
class once and then make many objects that belong to it. Objects are also known as
instances.
ne
➔ Member Variable − These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attributes of the object once an object is created.
➔ Member function − These are the functions defined inside a class and are used to
access object data.
la
➔ Inheritance − When a class is defined by inheriting the existing function of a parent
class then it is called inheritance. Here a child class will inherit all or few member
functions and variables of a parent class.
➔ Parent class − A class that is inherited from another class. This is also called a base
P
class or super class.
➔ Child Class − A class that inherits from another class. This is also called a subclass or
derived class.
➔ Polymorphism − This is an object oriented concept where the same function can be
fo
used for different purposes. For example, the function name will remain the same but
it takes a different number of arguments and can do different tasks.
➔ Overloading − a type of polymorphism in which some or all of operators have
different implementations depending on the types of their arguments. Similarly
functions can also be overloaded with different implementations.
In
Class
A class is a template for objects, and an object is an instance of class.
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 49
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.
Syntax:
<?php
class Fruit {
// code goes here...
}
?>
Example:
<?php
class Fruit {
// Properties
public $name;
public $color;
t
// Methods
ne
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
la
}
?>
P
Objects
Classes are nothing without objects! We can create multiple objects from a class.
Each object has all the properties and methods defined in the class, but they will have different
property values.
Objects of a class is created using the new keyword.
fo
Example;
<?php
class Fruit {
// Properties
public $name;
In
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Output:
Apple
Banana
Constructor
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class.
t
Notice that the construct function starts with two underscores (__)!
Example:
<?php
ne
class Fruit {
public $name;
public $color;
echo $apple->get_color();
?>
Output:
Apple
red
Destructor
A destructor is called when the object is destructed or the script is stopped or exited.
f you create a __destruct() function, PHP will automatically call this function at the end of the
script.
Notice that the destruct function starts with two underscores (__)!
Example:
<?php
class Fruit {
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 51
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
Output:
The fruit is Apple.
t
Access modifiers
In the PHP each and every property of a class in must have one of three visibility levels, known as
ne
public, private, and protected.
o Public: Public properties can be accessed by any code, whether that code is inside or outside
the class. If a property is declared public, its value can be read or changed from anywhere in
your script.
o Private: Private properties of a class can be accessed only by code inside the class. So if we
la
create a property that’s declared private, only methods and objects inside the same class can
access its contents.
o Protected: Protected class properties are a bit like private properties in that they can’t be
accessed by code outside the class, but there’s one little difference in any class that inherits
P
from the class i.e. base class can also access the properties.
Generally speaking, it’s a good idea to avoid creating public properties wherever possible. Instead, it’s
safer to create private properties, then to create methods that allow code outside the class to access
those properties. This means that we can control exactly how our class’s properties are accessed.
Note: If we attempt to access the property outside the class, PHP generates a fatal error.
fo
PHP Access Specifier’s feasibility with Class, Sub Class and Outside World :
Class Memmber Access Access from own class Accessible from Accessible by
Specifier derived class Object
Private Yes No No
Protected Yes Yes No
In
Inheritance
Inheritance is the way of extending the existing class functionality in the newly created class. We can
also add some additional functionality to the newly created class apart from extending the base class
functionalities. When we inherit one class, we say an inherited class is a child class (sub class) and
from which we inherit is called the parent class. The parent class is also known as the base class. This
is the way that enables the better management of the programming code and code reusability. The idea
behind using the inheritance is all about better management of the code and the code reusability. In
this topic, we are going to learn about Inheritance in PHP.
The child class will inherit all the public and protected properties and methods from the parent class.
In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 52
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}.";
}
}
t
// Strawberry is inherited from Fruit
ne
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
la
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
P
?>
arguments. But in case of function overriding, more than one functions will have same
method signature and number of arguments.
Function Overloading: Function overloading contains same function name and that function
performs different task according to number of arguments. For example, find the area of
In
certain shapes where radius are given then it should return area of circle if height and width
are given then it should give area of rectangle and others. Like other OOP languages function
overloading can not be done by native approach. In PHP function overloading is done with
the help of magic function __call(). This function takes function name and arguments.
Example:
<?php
// PHP program to explain function
// overloading in PHP
t
}
ne
$s = new Shape;
// Function call
echo($s->area(2));
echo "\n";
la
// calling area method for rectangle
echo ($s->area(4, 2));
?>
P
Output:
6.28
8
Function Overriding: Function overriding is same as other OOPs programming
languages. In function overriding, both parent and child classes should have same
fo
function name with and number of arguments. It is used to replace parent method in
child class. The purpose of overriding is to change the behavior of parent class
method. The two methods with the same name and same parameter is called
overriding.
In
Example:
<?php
// PHP program to implement
// function overriding
t
$c= new C;
ne
// print Parent
$p->geeks();
// Print child
$c->geeks();
la
?>
Output:
P
Parent
Child
fo
Object Cloning
An object copy is created by using the clone keyword (which calls the object’s __clone()
method if possible). An object’s __clone() method cannot be called directly. When an object
is cloned, PHP will perform a shallow copy of all of the object’s properties. Any properties
that are references to other variables will remain references.
In
Syntax:
t
$copy->data2 = "science ";
$copy->data3 = "portal";
ne
// Print values of $obj object
echo "$obj->data1$obj->data2$obj->data3\n";
Introspection
P
Introspection in PHP offers the useful ability to examine an object's characteristics, such as
its name, parent class (if any) properties, classes, interfaces, and methods.
PHP offers a large number of functions that you can use to accomplish the task.
The following are the functions to extract basic information about classes such as their name,
fo
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.
t
unserialize():
unserialize() can use string to recreate the original variable values i.e. converts actual data
ne
from serialized data.
Syntax:
unserialize(string);
<?php
$a=array('Shivam','Rahul','Vilas');
$s=serialize($a);
la
print_r($s);
$s1=unserialize($s);
echo "<br>";
P
print_r($s1);
?>
fo
In
HTML Forms
HTML Forms are required when you want to collect some data from the site visitor. For example
during user registration you would like to collect information such as name, email address, credit
card, etc.
A form will take input from the site visitor and then will post it to a back-end application such as
CGI, ASP Script or PHP script etc. The back-end application will perform required processing on
the passed data based on defined business logic inside the application.
There are various form elements available like text fields, textarea fields, drop-down menus,
t
radio buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following
ne
syntax:
Form Attributes:
P
attribute Description
method Method to be used to upload data. The most frequently used are GET and
POST methods.
target Specify the target window or frame where the result of the script will be
displayed. It takes values like _blank, _self, _parent etc.
In
enctype You can use the enctype attribute to specify how the browser
encodes the data before it sends it to the server. Possible values are:
There are different types of form controls that you can use to collect data using HTML
form: Text Input Controls
Single-line text input controls - This control is used for items that require only one line
of user input, such as search boxes or names. They are created using HTML <input> tag.
t
Ex. <input type="text" name="first_name" />
Attributes:
ne
➢ Name
➢ value
➢ size
➢ maxlength
la
Password input controls - This is also a single-line text input but it masks the character
as soon as a user enters it. They are also created using HTMl <input> tag.
➢ Name
➢ value
➢ size
➢ maxlength
fo
Multi-line text input controls - This is used when the user is required to give details that
may be longer than a single sentence. Multi-line input controls are created using HTML
<textarea> tag.
Attributes:
➢ Name
➢ rows
➢ cols
Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also
created using HTML <input> tag but type attribute is set to checkbox.
ex.
Attributes:
➢ Name
➢ value
➢ checked
Ex.
<form>
t
<input type="radio" name="subject" value="maths"> Maths
ne
</form>
Attributes:
➢ Name
➢ value
la
➢ checked
<select name="dropdown">
<option value="Physics">Physics</option>
</select>
Attributes of <select>:
In
➢ Name
➢ multiple
➢ size
➢ value
➢ selected
Attributes:
➢ name
➢ accepts
Button Controls
There are various ways in HTML to create clickable buttons. You can also create a
clickable button using <input> tag by setting its type attribute to button. The type attribute
can take the following values:
t
reset: This creates a button that automatically resets form controls to their initial values.
button: This creates a button that is used to trigger a client-side script when the user clicks
ne
that button.
Ex.
GET POST
In case of Get request, only limited amount of In case of post request, large amount of
data can be sent because data is sent in header. data can be sent because data is sent in
body.
Get request is not secured because data is Post request is secured because data is
exposed in URL bar. not exposed in URL bar.
Get request is more efficient and used more than Post request is less efficient and used
Post. less than get.
t
<body>
<form method="post" action="">
ne
<input type="text" name="produc">
<input type="submit">
</form>
</body>
</html>
P
<html>
<body>
fo
formaction=”savenext.php”>
</form>
</body>
</html>
t
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
ne
} else {
echo $name;
}
● Validate Numbers
$mobileno = $_POST ["Mobile_no"];
la
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
P
echo $mobileno;
}
● Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to
fo
validate the email address. Here, we will use regular expressions to validate the email
address.
<?php
$email = '[email protected]';
$pattern = "^[a-z0-9]+@[a-z0-9-]+\.[a-z0-9]+$^";
In
?>
● Input length
$mobileno = strlen ($_POST ["Mobile"]);
$length = strlen ($mobileno);
t
</style>
</head>
ne
<body>
<?php
// define variables to empty values
$nameErr = $emailErr = $mobilenoErr = $genderErr = $agreeErr = "";
la
$name = $email = $mobileno = $gender = $agree = "";
//String Validation
if (emptyempty($_POST["name"]))
fo
{
$nameErr = "Name is required";
}
else
{
In
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name))
{
$nameErr = "Only alphabets and white space are allowed";
}
}
//Email Validation
if (emptyempty($_POST["email"]))
{
$emailErr = "Email is required";
}
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 64
else
{
$email = input_data($_POST["email"]);
// check that the e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}
//Number Validation
if (emptyempty($_POST["mobileno"]))
{
t
$mobilenoErr = "Mobile no is required";
}
ne
else
{
$mobileno = input_data($_POST["mobileno"]);
// check if mobile no is well-formed
if (!preg_match("/^[0-9]*$/", $mobileno))
{
la
$mobilenoErr = "Only numeric value is allowed.";
}
//check mobile no length should not be less and greator than 10
P
if (strlen($mobileno) != 10)
{
$mobilenoErr = "Mobile no must contain 10 digits.";
}
fo
//Checkbox Validation
if (!isset($_POST['agree']))
{
$agreeErr = "Accept terms of services before submit.";
}
else
t
<h2>Registration Form</h2>
<span class = "error">* required field </span>
ne
<br><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
>
Name:
<input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
la
<br><br>
E-mail:
<input type="text" name="email">
P
<span class="error">* <?php echo $emailErr; ?> </span>
<br><br>
Mobile No:
<input type="text" name="mobileno">
fo
<br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
<span class="error">* <?php echo $genderErr; ?> </span>
<br><br>
Agree to Terms of Service:
<input type="checkbox" name="agree">
<span class="error">* <?php echo $agreeErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
<?php
if (isset($_POST['submit']))
{
if ($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == ""
&& $websiteErr == "" && $agreeErr == "")
{
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " . $name;
echo "<br>";
echo "Email: " . $email;
t
echo "<br>";
echo "Mobile No: " . $mobileno;
ne
echo "<br>";
echo "Website: " . $website;
echo "<br>";
echo "Gender: " . $gender;
}
else
la
{
echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
}
P
}
?>
</body>
fo
</html>
PHP COOKIE
PHP cookie is a small piece of information which is stored in a client browser. It is used to
In
t
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
ne
?>
</body>
</html>
Delete Cookie
If you set the expiration date in past, cookie will be deleted.
la
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
P
Advantages of Cookies :
1. Simple to Implement: Cookies are easy to implement. The fact that cookies are
supported on the client’s side means they are a lot easier to implement.
fo
2. Occupies Less Memory: Cookies do not require any server resources and are stored
on the user’s computer so no extra burden on the server.
3. Domain Specific: Each domain has its own cookies. There is no domain that shares
cookies with other domains. This makes them independent.
4. Simple to Use: Cookies are much simple and easier to use. This is the reason why
In
Disadvantages of Cookies:
1. Not Secured: As mentioned previously, cookies are not secure as they are stored in
the clear text they may pose a possible security risk as anyone can open and tamper
with cookies.
2. Difficult to Decrypt: We can manually encrypt and decrypt cookies, but it requires
extra coding and can affect application performance because of the time that is
required for encryption and decryption.
3. Limitations in Size: Several limitations exist on the size of the cookie text (4kb in
general), the number of cookies (20 per site in general). Each site can hold only
twenty cookies.
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 68
4. Can be Disabled: User has the option of disabling cookies on his computer from the
browser’s setting. This means that the user can decide not to use cookies on his
browser and it will still work.
5. Users can Delete Cookies: The fact that users can delete cookies from their
computers gives them more control over the cookies
SESSION
● A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
● When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session. The computer knows who you are. It knows
when you start the application and when you end. But on the internet there is one
t
problem: the web server does not know who you are or what you do, because the
HTTP address doesn't maintain state.
ne
● Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables last
until the user closes the browser.
● A session is started with the session_start() function.
● Session variables are set with the PHP global variable: $_SESSION.
la
Starting a PHP Session: The first step is to start up a session. After a session is started,
session variables can be created to store information. The PHP session_start() function is
used to begin a new session.It als creates a new session ID for the user.
P
Below is the PHP code to start a new session:
<?php
session_start();
?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal
fo
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>
Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling
session_start() and then by passing the corresponding key to the $_SESSION associative
array.
The PHP code to access a session data with two session variables Rollnumber and Name is
shown below:
<?php
session_start();
echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';
echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';
Destroying Certain Session Data: To delete only a certain session data,the unset feature can
be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session
array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
t
?>
ne
Destroying Complete Session: The session_destroy() function is used to completely destroy
a session. The session_destroy() function does not require any argument.
<?php
session_start();
session_destroy();
?>
la
Notes:
● The session IDs are randomly generated by the PHP engine .
P
● The session data is stored on the server therefore it doesn’t have to be sent with every
browser request.
● The session_start() function needs to be called at the beginning of the page, before
any output is generated by the script in the browser.
fo
SENDING EMAIL
In
PHP is a server side scripting language that is enriched with various utilities required.
Mailing is one of the server side utilities that is required in most of the web servers today.
Mailing is used for advertisement, account recovery, subscription etc.
In order to send mails in PHP, one can use the mail() method.
Syntax:
bool mail(to , subject , message , additional_headers , additional_parameters)
Parameters: The function has two required parameters and one optional parameter as
described below:
● to: Specifies the email id of the recipient(s). Multiple email ids can be passed using
commas
● subject: Specifies the subject of the mail.
PHP@Info_Planet Compiled by: Prasad Neve - 8275331362 Page | 70
● message: Specifies the message to be sent.
● additional-headers(Optional): This is an optional parameter that can create multiple
header elements such as From (Specifies the sender), CC (Specifies the CC/Carbon
Copy recipients), BCC (Specifies the BCC/Blind Carbon Copy Recipients. Note: In
order to add multiple header parameters one must use ‘\r\n’.
● additional-parameters(Optional): This is another optional parameter and can be
passed as an extension to the additional headers. This can specify a set of flags that
are used as the sendmail_path configuration settings.
● Return Type: This method returns TRUE if mail was sent successfully and FALSE
on Failure.
Example:
Sending a Simple Mail in PHP
<?php
t
$to = "[email protected]";
$sub = "Generic Mail";
$msg="Hello Geek! This is a generic email.";
ne
if (mail($to,$sub,$msg))
echo "Your Mail is sent successfully.";
else
echo "Your Mail is not sent. Try Again.";
?>
la
Sending a Mail with Additional Options
P
<?php
$to = "[email protected]";
$sub = "Generic Mail";
$msg = "Hello Geek! This is a generic email.";
$headers = 'From: [email protected]' . "\r\n" .'CC: [email protected]';
fo
if(mail($to,$sub,$msg,$headers))
echo "Your Mail is sent successfully.";
else
echo "Your Mail is not sent. Try Again.";
In
?>
What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.
The data in a MySQL database are stored in tables which consist of columns and rows.
● MySQL is a database system that runs on a server.
● MySQL is ideal for both small and large applications.
● MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
● MySQL compiles on a number of platforms.
Connecting to MySQL database using PHP
t
The mysqli_connect() function in PHP is used to connect you to the database. In the previous
version of the connection mysql_connect() was used for connection and then there comes
mysqli_connect() where i means improved version of connection and is more secure than
ne
mysql_connect().
mysqli_connect ( "host", "username", "password", "database_name" )
Parameters used:
● host: It is optional and it specifies the host name or IP address. In case of local server
localhost is used as a general keyword to connect local server and run the program.
la
● username: It is optional and it specify mysql username. In local server username is
root.
● Password: It is optional and it specify mysql password.
P
● database_name: It is database name where operation perform on data. It also
optional.
Return values:
It returns an object which represents a MySql connection. If the connection failed then it return
FALSE.
fo
<?php
$servername = "localhost";
$username = "username";
$password = "password";
In
$db=’php_diploma’;
$conn = mysqli_connect($servername, $username, $password,$db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
To close the connection in the mysql database we use the php function mysqli_close() which
disconnects from the database. It requires a parameter which is a connection returned by the
mysql_connect function.
t
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
ne
VALUES (value1, value2, value3,...)
Example:
<?php
la
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "php_diploma";
P
// Create connection
$link = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$link) {
fo
if (mysqli_query($link, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($link);
?>
Syntax:
$id=mysqli_insert_id($conn);
t
There are some MySQLi functions used to access data fetched with select query.
ne
1. mysqli_num_rows(mysqli_result $result) which returns a number of rows.
2. mysqli_fetch_row($result) returns a row as a numeric array. it returns null if there are no
more rows.
3. mysqli_fetch_assoc(mysqli_result $result) which returns a row as an associative array.
la
Each key of the array represents the column name of the table. It returns NULL if there
are no more rows.
4. mysqli_fetch_array($result) returns a row with the combination of numeric and
associative array.
P
Example:
<?php
$servername = "localhost";
fo
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
In
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " .
mysqli_close($conn);
?>
t
Update Query:
UPDATE table_name
ne
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example:
la
<?php
$servername = "localhost";
$username = "username";
$password = "password";
P
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
fo
Update Query:
Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$q = "UPDATE from users WHERE id=2";
$res=mysqli_query($conn, $sql)
t
if (mysqli_affected_rows($res)>0) {
echo "Record deleted successfully";
ne
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
la
P
fo
In