PHP Learning Unit 1,2
PHP Learning Unit 1,2
PHP Learning Unit 1,2
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to
create dynamic content that interacts with databases. PHP is basically used for developing web based
software applications.
PHP is a server-side and general-purpose scripting language that is especially suited for web
development.
PHP originally stood for Personal Home Page. However, now, it stands for Hypertext
Preprocessor. It’s a recursive acronym because the first word itself is also an acronym.
PHP was created by Rasmus Lerdorf in 1994. It’s currently maintained by the PHP Development
Team.
• First, the web browser sends an HTTP request to the web server, e.g., index.php.
• Second, the PHP preprocessor that locates on the web server processes PHP code to
generate the HTML document.
• Third, the web server sends the HTML document back to the web browser.
Advantages of PHP
Since PHP is designed for the web in the first place, it brings many advantages to web development:
[2]
History of IDE
Prior to IDEs, programmers wrote their programs in text editors. This involved writing and saving
an application in the text editor before running run the compiler, taking note of any error messages,
and then going back to the text editor to revise their code.
It wasn’t until 1983 that Borland Ltd. acquired a Pascal compiler and published it as TurboPascal,
featuring an integrated editor and compiler for the very first time.
TurboPascal may have launched the idea of an integrated development environment, but many
believe Microsoft’s Visual Basic (VB), which was launched in 1991, was actually the first real IDE
in history. Built in the older BASIC language, Visual Basic was a popular programming language
through the 1980s. The rise of Visual Basic meant that programming could instead be thought of in
graphical terms, and noteworthy productivity benefits became apparent.
There are many ways developers work to product the different types of code they produce, which
means there is also a variety of IDEs to use.
Multi-Language IDE
The multi-language IDEs – like Eclipse, Aptana, Komodo, NetBeans, and Geany – support multiple
programming languages.
[3]
• Eclipse: Supports C, C++, Perl, Python, Ruby, PHP, Java and others. It is a free and open
source editor for many development frameworks. Although it began as a Java development
environment, it has expanded through plugins. This IDE is managed and directed by the
Eclipse.org Consortium.
• NetBeans: Supports Java, PHP, JavaScript, C, C++, Python, Ruby, and more. It is also free
and open source. Modules provide all functions of the IDE. Developers can add support for
other programming languages by installing additional modules.
• Komodo IDE: Supports Perl, PHP, Python, Tcl, JavaScript, Ruby, and more. This is an
enterprise-level tool with a higher price point.
Specifically for mobile development, there are IDEs that include PhoneGap and Titanium Mobile
from Appcelerator.
A lot of IDEs, particularly multi-language IDEs, have mobile-development plugins. Eclipse, for
example, has this functionality.
HTML IDE
IDEs for developing HTML applications are some of the most popular IDEs around. For example,
DreamWeaver, HomeSite, and FrontPage automate numerous tasks involved in the process of
website development.
Cloud-Based IDE
Starting to become more mainstream, cloud-based IDEs are something to keep an eye on. The
capabilities of such web-based IDEs are growing rapidly; for that reason, most major vendors will
likely need to offer one if they want to stay competitive in their markets. Cloud IDEs are important
because they give programmers access to their code from anywhere.
For example, Nitrous is a cloud-based development environment platform that supports Ruby,
Python, Node.js and more. Cloud9 IDE supports more than 40 languages, including PHP, Ruby,
Python, JavaScript with Node.js, and Go. Heroku is a cloud-based development platform as a
service (PaaS), supporting several programming languages.
[4]
• Visual Studio: Supports VB.NET, Visual C++, C#, F# and more. Visual Studio is
Microsoft's IDE, designed to create apps for the Microsoft platform.
• MonoDevelop: Supports Visual Basic, C/C++, C#, and additional .NET languages.
• Xcode: Supports Swift and Objective-C languages, as well as Cocoa and Cocoa Touch
APIs. This IDE is solely for creating iOS and Mac applications. It includes a GUI builder
and an iPhone/iPad simulator.
• Espresso: Supports XML, HTML, CSS, PHP, and JavaScript. Espresso is a tool specifically
for Mac web programmers.
• Coda: Supports PHP, CSS, HTML, JavaScript, AppleScript, and Cocoa API. This IDE is
highlighted as "one-window development" for Mac users.
There are specific IDEs that cater to programmers who work in one language. These include Jikes
and Jcreator for Java, CodeLite and C-Free for C/C++, RubyMine for Ruby/Rails, and Idle for
Python.
Installing PHP on your computer allows you to safely develop and test a web application without
affecting the live system.
To work with PHP locally, you need to have the following software:
• PHP
• A web server that supports PHP. We’ll use the Apache webserver.
• A database server. We’ll use the MySQL database server.
Typically, you won’t install all this software separately because connecting them is tricky and not
intended for beginners.
Therefore, it’s easier to find an all-in-one software package that includes PHP, a web server, and a
database server. One of the most popular PHP development environments is XAMPP.
XAMPP is an easy install Apache distribution that contains PHP, MariaDB, and Apache webserver.
XAMPP supports Windows, Linux, and macOS.
[5]
First, open the folder htdocs under the xampp folder. Typically, it locates at C:\xampp\htdocs.
Third, create a new file called index.php under the helloworld folder and place the following code
in the file:
The code in the index.php file looks like a regular HTML document except the part <?php and ?> .
The code between the opening tag <?php and closing tag ?> is PHP:
This PHP code prints out the Hello, World message inside the h1 tag using the echo statement:
When PHP executes the index.php file, it evaluates the code and returns the Hello, World!message.
If you see the following on the web browser, then you’ve successfully executed the first PHP script:
If you view the soure code of the page, you’ll see the following HTML code:
Since the terminal doesn’t know how to render HTML to web, it just shows the pure HTML code.
To simplify the output, you can use the following code in the index.php:
PHP Syntax
As a programming language, PHP has a set of rules that governs how you write programs.
PHP code
Like HTML, you need to have the opening tag to start PHP code:
If you mix PHP code with HTML, you need to have the enclosing tag:
For example:
[8]
However, if a file contains only PHP code, the enclosing tag is optional:
Case sensitivity
PHP is partially case-sensitive. Knowing what are case sensitive and what is not is very important
to avoid syntax errors.
If you have a function such as count, you can use it as COUNT. It would work properly.
• PHP constructs such as if, if-else, if-elseif, switch, while, do-while, etc.
• Keywords such as true and false.
• User-defined function & class names.
On the other hand, variables are case-sensitive. e.g., $message and $MESSAGE are different
variables.
Statements
A PHP script typically consists of one or more statements. A statement is a code that does
something, e.g., assigning a value to a variable and calling a function.
[9]
A statement always ends with a semicolon (;). The following shows a statement that assigns a literal
string to the $message variable:
PHP Variables
A variable stores a value of any type, e.g., a string, a number, an array, or an object.
A variable has a name and is associated with a value. To define a variable, you use the following
syntax:
• The variable name must start with the dollar sign ($).
• The first character after the dollar sign ( $) must be a letter (a-z) or the underscore ( _ ).
• The remaining characters can be underscores, letters, or numbers.
PHP variables are case-sensitive. It means that $message and $Message variables are entirely
different.
To display the values of variables on a webpage, you’ll use the echo construct. For example:
[10]
Another shorter way to show the value of a variable on a page is to use the following syntax:
For example, the following shows the value of the $title variable in the heading:
[11]
Mixing PHP code with HTML will make the code unmaintainable, especially when the application
grows. To avoid this, you can separate the code into separate files. For example:
• index.php – store the logic for defining and assigning value to variables.
• index.view.php – store the code that displays the variables.
• Use the require construct to include the code from the index.view.php in the index.phpfile.
If you open the index.php file on the web browser, you’ll see the same output.
By doing this, you separate the code responsible for logic and the code responsible for displaying
the file. This is called the separation of concerns (SoC) in programming.
PHP Comments
Comments are important parts of the code. Comments provide useful information that will help you
and other developers understand the meaning of the code more quickly later.
• One-line comments
• Multi-line comments
One-line comments
The one-line comment is placed at the end of the line or at the current block.
A one-line comment starts with the pound (#) or double forward-slash (//). The rest of the text after
the (//) is ignored by the PHP interpreter.
Multi-line comments
A Multi-line comment start with /* and end with */. For example:
Summary
• Comments are important parts of the code because they explain why code does what it is
supposed to do.
• PHP supports both one-line and multi-line comments.
• A one-line comment starts with the # or // .
• A multi-line comment starts with /* and end with */.
PHP Constants
A constant is simply a name that holds a single value. As its name implies, the value of a constant
cannot be changed during the execution of the PHP script.
To define a constant, you use the define() function. The define() function takes the constant’s
name as the first argument and the constant value as the second argument. For example:
[14]
By convention, constant names are uppercase. Unlike a variable, the constant name doesn’t start
with the dollar sign($).
By default, constant names are case-sensitive. It means that WIDTH and width are different
constants.
In PHP 5, a constant can hold a simple value like a number, a string, a boolean value. From PHP
7.0, a constant can hold an array. For example:
PHP provides you with another way to define a constant via the const keyword. Here’s the syntax:
In this syntax, you define the constant name after the const keyword. To assign a value to a
constant, you use the assignment operator (=) and the constant value. The constant value can be
scalar, e.g., a number, a string, or an array.
The following example uses the const keyword to define the SALES_TAX constant:
[15]
A type specifies the amount of memory that allocates to a value associated with it. A type also
determines the operations that you can perform on it.
PHP has ten primitive types including four scala types, four compound types, and two special types:
Scalar types
A variable is a scalar when it holds a single value of the type integer, float, string, or boolean.
Integer
Integers are whole numbers defined in the set {…-3,-2-,-1,0,1,2,3…}. The size of the integer
depends on the platform where PHP runs.
The constant PHP_INT_SIZE specifies the size of the integer on a specific platform. PHP uses the
int keyword to denote the integer type.
Float
Floats are floating-point numbers, which are also known as floats, doubles, or real numbers.
PHP uses the float keyword to represent the floating-point numbers. The following example
illustrates the floating-point numbers in PHP:
Boolean
Boolean represents a truth value that can be either true or false. PHP uses the bool keyword to
represent the Boolean type.
The bool type has two values true and false. Since keywords are case-insensitive, you can
use true, True, TRUE, false, False, and False to indicate boolean values.
String
A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“). For
example:
An operator takes one or more values, known as operands, and performs a specific operation on
them.
For example, the + operator adds two numbers and returns the sum of them.
• Arithmetic Operators
• Assignment Operators
• Bitwise Operators
• Comparison Operators
• Increment/Decrement Operators
• Logical Operators
• Concatenating Operators
• Arithmetic Operators
• The arithmetic operators require numeric values. If you apply them to non-numeric values,
they’ll convert them to numeric values before carrying the arithmetic operation.
• The following are the list of arithmetic operators:
[18]
% Modulus Return the remainder of the division of the first operand by the
second one
Comparison Operators
A comparison operator returns a Boolean value, either true or false. If the comparison is truthful,
the comparison operator returns true, otherwise, it returns false.
== Equality Return true if both operands are equal, otherwise returns false.
=== Identity Return true if both operands have the same data type and equal, otherwise
return false.
!=== Not identical Return true if both operands are not equal or not have the same data type,
otherwise returnfalse.
> Greater than Return true if the operand on the left is greater than the operand on the right,
otherwise return false.
[20]
>= Greater than or Return true if the operand on the left is greater than or equal to the operand on
equal to the right, otherwise return false.
< Less than Return true if the operand on the left is less than the operand on the right,
otherwise return false.
<= Less than or equal Return true if the operand on the left is less than or equal to the operand on the
right, otherwise return false.
Logical Operators
Logical operators allow you to construct logical expressions. A logical operator returns a Boolean
value.
&& Logical Return true if both operands are true, otherwise return false. If the first operand is false, it
AND will not evaluate the second operand because it knows for sure that the result is going to
be false. This is known as short-circuiting.
|| Logical Return true if one of the operands is true, otherwise returns false. If the first operand
OR is true, it will not evaluate the second one.
xor Logical Return true if either operand, not both, is true, otherwise, return false.
XOR
! Not returns true if the operand is false, and returns false if the operand is true.
Bitwise Operators
[21]
Bitwise operators perform operations on the binary representation of the operands. The following
illustrates bitwise operators in PHP:
$x & $y And If both bits are 1, the corresponding bit in the result is 1; otherwise, the
corresponding bit is 0
$x | $y Or (inclusive If both bits are 0, the corresponding bit in the result is 0; otherwise, the
or) corresponding bit is 1
$x ^ $y Xor (exclusive If either bit, but not both, in $x and $y are 1, the corresponding bit in the result is 1;
or) otherwise, the corresponding bit is 0
$x << $y Shift left Shifts the bits in $x left by the number of places specified by $y.
$x >> $y Shift right Shifts the bits in $x right by the number of places specified by $y.
Increment (++) and decrement (–) operators give you a quick way to increase and decrease the
value of a variable by 1.
Concatenating Operator
Concatenating operator (.) allows you to combine two strings into one. It appends the second string
to the first one and returns the combined string. For example:
Assignment Operators
Assignment operator ( =) assigns a value to a variable and returns a value. The operand on the left is
always a variable, while the operand on the right can be a literal value, variable, expression, or a
function call that returns a value. For example:
In the first expression, we assigned $x variable value 10. In the second one, we assigned the value
of $x to $y variable. The third one is a little bit complicated. First, we assigned 20 to $x. The
assignment operator (=) returns 20 and then 20 is assigned to $z variable.
Besides the basic assignment operator (=), PHP provides you with some assignment operators:
• plus-equal +=
• minus-equal -=
• divide-equal /=
[23]
• multiplication-equal *=
• modulus-equal %=
• XOR-equal ^=
• AND-equal &=
• OR-equal |=
• concatenate-equal .=
The precedence of an operator decides which order the operator is evaluated in an expression.
PHP assigned each operator precedence. Some operators have the same precedence, e.g.,
precedences of the addition ( +) and subtraction( -) are equal.
For example, the precedence of the multiplication operator ( *) is higher than the precedence of the
add( +) and the subtract ( -) operators:
Because the precedence of the multiplication operator ( *) is higher than the precedence of the
add( +) operator, PHP evaluates the multiplication operator ( *) first and then add operator ( *)
second.
To force the evaluation in a particular order, you put the expression inside parentheses (), for
example:
PHP uses the = to represent the assignment operator. The following shows the syntax of the
assignment operator:
On the left side of the assignment operator (=) is a variable to which you want to assign a value.
And on the right side of the assignment operator (=) is a value or an expression.
When evaluating the assignment operator (=), PHP evaluates the expression on the right side first
and assigns the result to the variable on the left side. For example:
In this example, we assigned 10 to $x, 20 to $y, and the sum of $x and $y to $total.
The assignment expression returns a value assigned, which is the result of the expression in this
case:
It means that you can use multiple assignment operators in a single statement like this:
The assignment expression $y = 20 returns 20 so PHP assigns 20 to $x. After the assignments,
both $x and $y equal 20.
How it works.
PHP provides the arithmetic assignment operator += that can do the same but with a shorter code.
For example:
Besides the += operator, PHP provides other arithmetic assignment operators. The following table
illustrates all the arithmetic assignment operators:
+= $x += $y $x = $x + $y Addition
-= $x -= $y $x = $x – $y Subtraction
[26]
*= $x *= $y $x = $x * $y Multiplication
/= $x /= $y $x = $x / $y Division
%= $x %= $y $x = $x % $y Modulus
A comparison operator allows you to compare two values and returns true if the comparison is
truthful and false otherwise.
== Equal to Return true if both operands are equal; otherwise, it returns false.
!=, <> Not equal to Return true if both operands are equal; otherwise, it returns false.
=== Identical to Return true if both operands have the same data type and equal; otherwise, it
returns false.
!== Not identical to Return true if both operands are not equal or not have the same data type;
otherwise, it returns false.
> Greater than Return true if the operand on the left is greater than the operand on the right;
otherwise, it returns false.
[27]
>= Greater than or Return true if the operand on the left is greater than or equal to the operand on
equal to the right; otherwise, it returns false.
< Less than Return true if the operand on the left is less than the operand on the right;
otherwise, it returns false.
<= Less than or equal Return true if the operand on the left is less than or equal to the operand on the
to right; otherwise, it returns false.
The equality returns true if both values are equal; otherwise, it returns false. The following example
returns true because 10 is equal 10:
If you want to compare two values with the consideration of type, you can use the identical operator
(===).
[28]
The not equal to (!=, <>) operator returns true if the lefthand value is not equal to the righthand
value; otherwise, it returns false. For example:
The greater than return true if the lefthand value is greater than the righthand value; otherwise, it
returns false:
The greater than or equal to operator returns true if the lefthand value is greater than or equal to the
righthand value; otherwise, it returns false. For example:
[29]
The less than operator returns true if the lefthand value is less than the righthand value; otherwise, it
returns false. For example:
If the lefthand value is less than or equal to the righthand value, the less than or equal to operator
returns true; otherwise, it returns false. For example:
[30]
The logical AND operator accepts two operands and returns true if both operands are true;
otherwise, it returns false.
PHP uses the and keyword to represent the logical AND operator:
In addition to using the and keyword, PHP uses && as the logical AND operator:
The && and and operators return the same result. The only difference between
the && and andoperators are their precedences.
The and operator has higher precedence than the && operator. The precedence of an operator
specifies the order in which PHP evaluates.
PHP OR operator
[31]
he logical OR operator accepts two operands and returns true if either operand is true; otherwise, it
returns false. In other words, the logical OR operator returns false if both operands are false.
To represent the logical OR operator, PHP uses either the or keyword or the || as follows:
Or
Note that the or, Or, and OR are the same because PHP keywords are case-insensitive.
The || and or operators return the same result. The only difference between the || and oroperators are
their precedences. The or operator has higher precedence than the || operator.
Conditional statements are used to perform different actions based on different conditions. In PHP
we have the following conditional statements:
[32]
PHP If statement
Syntax:
if (condition) {
code to be executed if condition is true;
}
<?php
$mark = 15;
PHP if else
if...else statement that executes a code block when a condition is true or another code block when
the condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<?php
$t = 4;
[33]
if ($t%2 == 0) {
echo $t": is Even number";
} else {
echo $t": is Even number";
}
?>
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) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
<?php
$x = 20;
$y = 30;
Use the switch statement to select one of many blocks of code to be executed.
[34]
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
First, we have a single expression n (most often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure. If there is a match, the
block of code associated with that case is executed. Use break to prevent the code from running
into the next case automatically. The default statement is used if no match is found.
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
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!";
}
?>
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
[35]
Loops are used to execute the same block of code again and again, as long as a certain condition is
true. In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition) {
code to be executed;
}
Example:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Syntax:
do {
code to be executed;
} while (condition);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or
equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
[36]
Example:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Syntax:
Parameters:
Example:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Syntax:
Example:
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array ($colors):
<?php
$colors = array("red", "green", "blue", "yellow");
An array is a special variable, which can hold more than one value at a time.
array();
The index can be assigned automatically (index always starts at 0), like this:
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Multidimensional Arrays
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However,
arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
Two-dimensional Arrays
Volvo 22 18
BMW 15 13
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
[39]
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Land Rover",17,15)
);
Example:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still
have to point to the two indices):
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
2.5.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. There are thousands of built-in functions in PHP.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.
Please check out our PHP reference for a complete overview of the PHP built-in functions.
Besides the built-in PHP functions, it is possible to create your own functions.
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
Information can be passed to functions through arguments. An argument is just like a variable.
[41]
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
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.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Example:
[42]
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.
html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
</body>
</html>
A session is a way to store information (in variables) to be used across multiple pages.
Importance of PHP Session
1. Limit the number of logins
For instance if your application should allow only 10 logins at a time , then the session table
can be checked to find the number of users already logged in. If the limit is exceeded, then
further users may not be allowed to log in.
2. Block multiple logins for same username.
If your website or application needs to make a user login from only 1 location at a time for
security purpose or something else , then the sessions table can simply delete the earlier
session data of a particular username and login the new one.
3. Monitor user activity
View which user is currently online, when did he login and for how long has he been active.
4. Logout a user
A user can be logged out simply by removing his session entry in the database. This can be
useful to logout users who have been inactive for a long time
Where to apply PHP session
Starting a PHP Session
It is recommended to put the call to session_start () at the beginning of the page. Session
variables are stored in associative array called $_SESSION[]. These variables can be accessed
during lifetime of a session.
CREATING PHP SESSION USING ISSET()
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
Example 2:
<? php
session_start();
<html>
<head>
<title> PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION ["favcolor"] = "green";
$_SESSION ["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
PHP VARIABLES
[45]
<? PHP
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
MODIFYING PHP SESSION VARIABLE
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
A PHP session can be destroyed by session_destroy() function. This function does not need
any argument and a single call can destroy all the session variables. If you want to destroy a
single session variable then you can use unset() function to unset a session variable.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
[46]
A regular expression is a sequence of characters that forms a search pattern. When you search for
data in a text, you can use this search pattern to describe what you are searching for.
PHP provides a variety of functions that allow you to use regular expressions. The preg_match(),
preg_match_all() and preg_replace()functions are some of the most commonly used ones:
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also
be 0
preg_replace() Returns a new string where matched patterns have been replaced with another
string
PHP string functions allow you to test if a string contains a substring (str_contains()) or to replace
all occurrences of a substring with another string (str_replace()).
However, these functions deal with fixed patterns. They won’t work with flexible patterns. For
example, if you want to search any numbers in a string, the str_contains() won’t work.
A regular expression is a string that describes a pattern such as phone numbers, credit card numbers,
and email addresses.
For example:
[47]
The $pattern is a string. Also, it is a regular expression that matches a number with one or more
digits. For example, it matches the numbers 1, 20, 300, etc.
Note that you’ll learn how to form flexible regular expressions in the following tutorial.
The forward-slashes are delimiters. The delimiters can be one of the following characters ~, !, @, #,
$ or braces including {}, (), [], <>. The braces help improve regular expressions’ readability in
some cases. Note that you cannot use the alphanumeric, multi-byte, and backslashes (\) as
delimiters.
Search strings using regular expressions to search a string for a match to a pattern, you use the
preg_match() and preg_match_all()functions.
To search based on a regular expression, you use the preg_match() function. For example:
Output:
[48]
The preg_match() searches the $message for a match to the $pattern. The preg_match() function
returns 1 if there is a match in the $message, 0 if it doesn’t, or false on failure.
To get the text that matches the pattern, you add the third parameter to the preg_match() function
like the following example:
Output:
The $matches parameter contains all the matches. The $matches[0] stores the text that matches the
pattern. In this example, it is the number 8.
The $matches[1], $matches[2], ….. store the texts that match the first, second,…. The preg_match()
only returns the first match and stops searching as soon as it finds the first one. To find all matches,
you use the preg_match_all() function.
The preg_match_all() function searches for all matches to a regular expression. For example:
[49]
Output:
In this example, the preg_match_all() puts all matches in a multidimensional array with the first
element contains the texts (8, 26 and 2020) that match the pattern.
The preg_match_all() function returns the number of matches, which can be zero or a positive
number.
To replace strings that match a regular expression, you use the preg_replace() function. For
example:
[50]
Output:
In this example, the preg_replace() function replaces all numbers in the $message with the
string %d.
2.8.Form handling
➢ Action: specifies the URL that processes the form submission. In this example, the
form.php will process the form.
➢ method: : specifies the HTTP method for submitting the form. The most commonly used
form methods are POST and GET. In this example, the form method is post.
In this example, the form method is post or POST . If you don’t specify the method attribute, the
form element will use the get method by default.
Typically, a form has one or more input elements including text, password, checkbox, radio
button, select, file upload, etc. The input elements are often called form fields.
Typically, a form has one or more input elements including text, password, checkbox, radio
button, select, file upload, etc. The input elements are often called form fields.
An input element has the following important attributes name, type and value. The name attribute
will be used for accessing the value in PHP.
If a form uses the POST method, the web browser will include the form data in the HTTP request’s
body. After submitting the form, you can access the form data via the associative array $_POST in
PHP.
For example, if a form has an input element with the name email, you can access the email value in
PHP via the $_POST['email'] . If the form doesn’t have an email input, the $_POST won’t have any
element with the key 'email'.
[51]
To check if the form data contains the email, you use the isset() like this:
In the form.php file, you can access the email value as follows:
When you submit a form using the GET method, you can access the form data in PHP via the
associative array $_GET. Unlike the POST method, the GET method appends the form data in the
URL that processes the form. Suppose the URL that processes the form is http://localhost/form.php
and submit a form, you’ll see that the email value is appended to the URL.
In PHP, you can use the isset() to check if the form data contains the email:
[52]
If the form has multiple input elements, the web browser will append the form inputs to the URL in
the following format:
The following shows the same form that has an email input. However, the form uses the GET
method instead:
Note that both $_POST and $_GET arrays are superglobal variables. It means that you can access
them anywhere in the script.
In general, you should use the GET method when the form only retrieves data from the server. For
example, a search form that allows users to search for information should use the GET method.
When you have a form that causes a change in the server, you should use the POST method. For
example, a form that allows users to subscribe to a newsletter should use the POST method.
[53]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<link rel="stylesheet" href="css/style.css">
<title>PHP Form</title>
</head>
<body>
<main>
<form action="subscribe.php" method="post">
<div>
<label for="name">Name:</label>
<input type="text" name="name" required="required"
placeholder="Enter your name" />
</div>
<div>
<label for="name">Email:</label>
<input type="email" name="email" required="required"
placeholder="Enter your email" />
</div>
<button type="submit">Subscribe</button>
</form>
</main>
</body>
</html>
The form uses the POST method and submits the data to the subscribe.php page. It has two input
elements with type text and email.
Before submitting the form to the server, the web browser checks if all required fields are filled out,
in the correct format. This is known as client-side form validation.
To validate data on the client-side, you can use either HTML5 form validation or JavaScript
validation. However, you should never rely on client-side validation as a security measure.
The client-side validation’s purpose is to help legitimate users to enter data in the correct format.
However, it doesn’t prevent malicious users from entering bad data that potentially harm the
application. Therefore, it’s mandatory to implement server-side validation.
How it works.
• First, check if the name and email are in the $_POST array using the isset() function.
• Second, show a thank you message.
Sometimes, you want to include both form and logic for handling form submission in a single PHP
file. This form is often referred to as a self-processing form.
To create a self-processing form, you can use the $_SERVER['REQUEST_METHOD'] that returns
the request method e.g., GET or POST.
To make the code more organized, you can create the following file & directory structure:
The index.php file in the root directory will include the header.php and footer.php.
If the request method is GET , the index.php file loads the form in the get.php file. Otherwise, it
loads the code from the post.php file for processing the POST request.