Unit II PHP
Unit II PHP
PHP is a server-side scripting language, which means that a web server executes the
PHP script and then sends the resulting HTML to the browser. PHP is used in over 75% of
websites that use a server-side programming language.
PHP, or Hypertext Preprocessor, is a scripting language that can perform a variety of
tasks for web development, including:
Dynamic content: PHP can generate dynamic web pages that change based on user
input or other factors
Database management: PHP can store, delete, and modify data in a database
Form handling: PHP can collect and validate form data
Cookies: PHP can send and receive cookies
User authentication: PHP can store and retrieve usernames and passwords, and
support two-step verification
Data encryption: PHP can encrypt data
File management: PHP can create, open, read, write, delete, and close files on the
server
Emailing: PHP can send emails
Advantages:
Platform Independent
Open source and dynamic Library support
Organized
Database Connectivity
Easy to understand and code
Gives Web Developer More Control
Easy integration and consistency
Maintenance
Stability
Performance
Reliability
Scalability
Compatibility
Disadvantages of PHP
Inconsistency
Security Concerns
Performance
Lack of Modern Features
Scalability Challenges
Not Suitable for Large-Scale Applications
Limited Object-Oriented Programming (OOP) Support
Syntax of PHP
<?php
// PHP code goes here
?>
Basic Example of PHP
<html>
<head>
<title>PHP Hello World</title>
</head>
<body>
<?php echo "Hello, World! This is PHP code";?>
</body>
</html>
Output:
Hello, World! This is PHP code
Characteristics of PHP
PHP code is executed in the server.
It can be integrated with many databases such as Oracle, Microsoft SQL Server,
MySQL, PostgreSQL, Sybase, and Informix.
It is powerful to hold a content management system like WordPress and can be used
to control user access.
It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others.
Websites like www.facebook.com and www.yahoo.com are also built on PHP.
One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.
The thing that differentiates PHP from the client-side language like HTML is, that
PHP codes are executed on the server whereas HTML codes are directly rendered on
the browser. PHP codes are first executed on the server and then the result is returned
to the browser.
The only information that the client or browser knows is the result returned after
executing the PHP script on the server and not the actual PHP codes present in the
PHP file. Also, PHP files can support other client-side scripting languages like CSS
and JavaScript.
Features of PHP
Open-Source and Free: PHP is firstly open source which means anyone can use
PHP code without any licensing. Along with this one can run PHP on any operating
system like Windows, macOS, Linux, Unix and more.
PHP Server-Side Scripting: PHP code executes on the server before sending
HTML content to the user's browser, allowing for the dynamic generation of web
pages and handling user interactions.
Interpreted language: PHP code is interpreted line by line, eliminating the need for
compilation and simplifying development and testing processes.
Database connectivity: PHP integrates seamlessly with various databases like
MySQL, PostgreSQL, and Oracle, facilitating data storage and retrieval for web
applications.
Object-oriented programming (OOP): PHP supports OOP concepts like classes,
objects, inheritance, and polymorphism, enabling better code organization and
modularity.
Built-in functions: PHP comes with a rich set of built-in functions for various tasks
such as string manipulation, date and time handling, file handling, and more,
reducing the need for external libraries.
Session management: PHP allows for user session management, enabling
personalized experiences and storing user data across multiple page visits.
Security features: While security considerations are essential for any development
language, PHP offers several built-in security features and best practices to help
mitigate vulnerabilities
Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.
Cross-Platform: PHP runs on various platforms, making it compatible with different
operating systems.
Database Integration: PHP provides built-in support for interacting with databases,
such as MySQL, PostgreSQL, and others.
Applications of PHP
PHP is versatile and can be used in a variety of web development scenarios,
including:
Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.
Content Management Systems (CMS): Many popular CMSs like WordPress,
Joomla, and Drupal are built with PHP.
E-commerce Platforms: PHP is commonly used to develop e-commerce websites
due to its database integration capabilities.
Web Applications: PHP is used for creating feature-rich web applications such as
social media platforms, forums, and customer relationship management (CRM)
systems.
API Development: PHP can be used to create APIs for web and mobile applications.
3 Language Basics
Lexical Structure:
The lexical structure in PHP refers to the set of rules and conventions that dictate how
the PHP source code should be written and structured. Understanding PHP's lexical structure
is crucial for writing valid and readable code. Here are some key aspects of PHP's lexical
structure:
1. Case Sensitivity:
The names of user-defined classes and functions, as well as built-in constructs and
keywords such as echo, while, class, etc., are case-insensitive. Thus, these three lines are
equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are
three different variables.
2. Semicolons:
Statements in PHP are terminated with a semicolon ;. Omitting the semicolon at the
end of a statement can lead to syntax errors.
$variable = 42; // Valid
echo "Hello, World"; // Valid
3. Whitespace:
PHP is relatively lenient when it comes to whitespace, but it's essential for code
readability. You can use spaces, tabs, and line breaks to format your code as needed.
$variable = 42; // This is well-formatted
$variable=42; // This is valid but less readable
4. Comments:
PHP supports two types of comments:
Single-line comments: These begin with // and extend to the end of the line.
Multi-line comments: These start with /* and end with */. Multi-line comments can
span multiple lines and are often used for documentation.
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two
values: TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition
is correct, it returns TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
This condition is TRUE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole
numbers, i.e., numbers without fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
Addition of floating numbers: 73.812
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and
even special characters. String values must be enclosed either within single quotes or
in double quotes. But both are treated differently. To clarify this, see the example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
2 PHP Data Types: Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
PHP Array
An array is a compound data type. It can store multiple values of same data type in a
single variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and valu
es
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=>
string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Bike Model: Royal Enfield
3 PHP Data Types: Special Types
There are 2 special data types in PHP.
1. resource
2. NULL
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some
function calls or references to external PHP resources. For example - a database call. It is an
external resource.This is an advanced topic of PHP, so we will discuss it later in detail with
examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive. The special type of data type NULL defined
a variable with no value.
Example:
<?php
$nm = NULL;
echo $nm; // this will return no output
?>
Output:
NULL
5 Variables
PHP Variables are one of the most fundamental concepts in programming. It is used
to store data that can be accessed and manipulated within your code. Variables in PHP are
easy to use, dynamically typed and essential for creating dynamic, interactive web
applications.
Declaring Variables in PHP
To declare a variable in PHP, you simply assign a value to it using the $ symbol
followed by the variable name. PHP variables are case-sensitive and must start with a letter or
an underscore, followed by any number of letters, numbers, or underscores.
Example
<?php
$name = "XYZ"; // String
$age = 30; // Integer
$salary = 45000.50; // Float
$isEmployed = true; // Boolean
?>
$sum++;
$num++;
4. Superglobals
Superglobals are built-in arrays in PHP that are accessible from anywhere in the
script, including within functions. Common superglobals include $_GET, $_POST,
$_SESSION, $_COOKIE, $_SERVER, and $_GLOBALS.
<?php
// Using $_SERVER superglobal to
// get server information
echo $_SERVER['SERVER_NAME'];
?>
Variable Variables
PHP allows us to use dynamic variable names, called variable variables.
Variable variables are simply variables whose names are dynamically created by
another variable’s value.
Example: This example shows the declaration of a variable by the use of another variable.
<?php
$a = 'hello'; //hello is value of variable $a
$$a = 'World'; //$($a) is equals to $(hello)
echo $hello; //$hello is World i.e. $hello is new variable with value 'World'
?>
Output
World
// Addition
echo "Addition: " . ($x + $y) . "\n";
// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";
// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";
// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";
// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1
Logical or Relational Operators:
These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or cannot
be met so the result of a conditional statement can either be true or false. Here are the logical
operators along with their syntax and operations in PHP.
Logical
! !$x True if $x is false
NOT
Example: This example describes the logical & relational operator in PHP.
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";
if ($x == 50 or $y == 20)
echo "or Success \n";
if ($x == 50 || $y == 20)
echo "|| Success \n";
if (!$z)
echo "! Success \n";
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success
Comparison Operators:
These operators are used to compare two elements and outputs the result in boolean
form. Here are the comparison operators along with their syntax and operations in PHP.
Assignment Operators:
These operators are used to assign values to different variables, with or without mid-
operations. Here are the assignment operators along with their syntax and operations, which
PHP provides for the operations.
Operator Name Syntax Operation
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used to
compare values but instead of returning the boolean results, it returns integer values. If both
the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left
operand is greater, it returns 1. The following table shows how it works in detail:
Example: This example illustrates the use of the spaceship operator in PHP.
<?php
$x = 50;
$y = 50;
$z = 25;
echo $x <=> $y;
echo "\n";
Array Operators:
These operators are used in the case of arrays. Here are the array operators along with
their syntax and operations that PHP provides for the array operation.
var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used
to increment or decrement values.
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";
$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:
String Operators:
This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.
Operator Name Syntax Operation
2 Expressions
Almost everything in a PHP script is an expression. Anything that has a value is an
expression. In a typical assignment statement ($x=100), a literal value, a function or operands
processed by operators is an expression, anything that appears to the right of assignment
operator (=)
Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
8 Flow-Control Statements
Flow control statements in PHP are used to control the order in which code is
executed. There are three types of flow control statements in PHP:
Conditional statements: These statements execute a block of code based on certain
conditions. Examples include if, else, and switch statements.
Loop statements: These statements execute a block of code repeatedly based on
certain conditions. Examples include for, while, do-while, and foreach loops.
Jump statements: These statements transfer control to another part of the code.
Conditional statements
PHP provides us with four conditional statements:
if statement
if…else statement
if…elseif…else statement
switch statement
1 if Statement:
This statement allows us to set a condition. On being TRUE, the following block of
code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
Example:
<?php
$x = 12;
if ($x > 0) {
echo "The number is positive";
}
?>
Output:
The number is positive
Flowchart:
2 if…else Statement:
We understood that if a condition will hold i.e., TRUE, then the block of code within
if will be executed. But what if the condition is not TRUE and we want to perform an action?
This is where else comes into play. If a condition is TRUE then if block gets executed,
otherwise else block gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:
<?php
$x = 12;
if ($x > 0) {
echo "The number is positive";
}else{
echo "The number is negative";
}
?>
Output:
The number is negative
Flowchart:
3 if…elseif…else Statement:
This allows us to use multiple if…else statements. We use this when there are
multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
elseif ($x == "August") {
echo "Happy Independence Day!!!";
}
else{
echo "Nothing to show";
}
?>
Output:
Happy Independence Day!!!
Flowchart:
4 switch Statement:
The “switch” performs in various cases i.e., it has various cases to which it matches
the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same
case is executed. To use switch, we need to get familiar with two different keywords namely,
break and default.
1. The break statement is used to stop the automatic control flow into the next cases and
exit from the switch case.
2. The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example:
<?php
$n = "February";
switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>
Output:
Its February
Flowchart:
Loop statements
PHP Loops are used to repeat a block of code multiple times based on a given
condition. PHP provides several types of loops to handle different scenarios, including while
loops, for loops, do…while loops, and foreach loops.
PHP provides us with four Loop statements:
for Loop
while Loop
do-while Loop
foreach Loop
?>
Output
12345
Syntax
while ( condition ) {
// Code is executed
}
$num = 1;
?>
Output
12345
$num = 1;
do {
echo $num . " ";
$num++;
} while ($num <= 5);
?>
Output
12345
Syntax:
foreach ( $array as $key => $value ) {
// Code to be executed
}
echo "\n";
?>
Output
10 20 30 40 50 60
John => 25
Alice => 30
Bob => 22
Jump statements
Jump statement is a control flow statement in programming that alters the normal
sequential execution of code by transferring program control to a different part of the code.
Jump statements include commands like "break," "continue," "return," and "goto," each
serving specific purposes:
break: Terminates the current loop iteration or exits a switch statement, transferring
control to the statement immediately following the loop or switch block.
continue: Skips the rest of the current loop iteration and proceeds to the next iteration
of the loop.
return: Exits a function prematurely and returns a value, if specified, to the caller.
goto: Allows transferring control to a labeled statement within the same function or
block, though its usage is discouraged in modern programming due to potential
complications in code readability and maintenance.
1 PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch,
and for-each loop. The break keyword immediately ends the execution of the loop or switch
structure. It breaks the current flow of the program at the specified condition and program
control resumes at the next statements outside the loop. The break statement can be used in
all types of loops such as while, do-while, for, foreach loop, and also with switch case.
Syntax
jump statement;
break;
Syntax:
statement_1;
if (expr)
goto label;
statement_2;
statement_3;
label: statement_4;
Example
#include <stdio.h>
int getResult()
{
int result = 10;
if (result > 0) {
return result; // Return a positive value
}
}
int main()
{
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the remaining code for i=3
}
printf("%d ", i);
if (i == 4) {
break; // Exit the loop when i=4
}
}
return 0;
}
9 Working with include and require construct
It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with include or require statement.
In PHP, you can include code from one file within another file using various
techniques. This is a powerful way to reuse code, organize your project into manageable
parts, and maintain code modularity. Here are the primary methods for including code in
PHP:
1. include Statement:
The include statement is used to include and execute code from another file. If the included
file is not found, it generates a warning but allows the script to continue.
Syntax:
include 'filename.php';
Example :
include 'header.php';
// Rest of your PHP code
include 'footer.php';
2. require Statement:
The require statement is similar to include, but if the included file is not found, it
generates a fatal error and terminates the script.
Syntax:
require 'filename.php';
Example :
require 'config.php';
// Rest of your PHP code
require 'database.php';
Example :
include_once 'functions.php';
// Rest of your PHP code
include_once 'functions.php';
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
Output
Welcome to my home page!
Some text.
Some more text.
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will continue to
execute:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
Output
Welcome to my home page!
I have a
If we do the same example using the require statement, the echo statement will not be
executed because the script execution dies after the require statement returned a fatal error:
Example
<html>
<body>
</body>
</html>
Output
Welcome to my home page!
Difference between require() and include()
include()
require()
The include() function does not stop the The require() function will stop the
execution of the script even if any error execution of the script when an
occurs. error occurs.
The include() function does not give a The require() function gives a fatal
fatal error. error
2. SGML Style:
In SGML-style, PHP code is enclosed within HTML-like comment tags, which makes
it easy to read but may not be as syntactically clean.
Components of SGML:
SGML provides a way of describing the relationships between these entities,
elements, and attributes, and tells the computer how it can recognize the
component parts of a document and it is based on the concept of a document
being composed of a series of entities (object).
It provides rules that allow the computer to recognize where the various
elements of a text entity start and end.
Document Type Definition (DTD) in SGML is used to describe each element
of the document in a form that the computer can understand.
SGML is the simplest medium to produce files that can be read by people and
exchanged between machines and applications in a straightforward manner. It is
easy to understand by the human as well as the machine.
Structure of SGML:
<mainObject>
<subObject>
</subObject>
</mainObject>
The extension of SGML files is:
File_Name.sg
ml
Example:
<!DOCTYPE html>
<html>
<head>
<title>SGML-Style PHP</title>
</head>
<body>
<p><!--
<?php
echo "Hello, World!";
?>
--></p>
</body>
</html>
3. ASP Style:
PHP can also be embedded in a style similar to ASP (Active Server Pages). PHP code
is enclosed within <% and %> tags.
Syntax:
<%
// Your PHP code here
%>
Example:
<!DOCTYPE html>
<html>
<head>
<title>ASP-Style PHP</title>
</head>
<body>
<p>
<%
echo "Hello, World!";
%>
</p>
</body>
</html>
4. Script Style:
In script style, PHP code is embedded using the <script> element, similar to JavaScript.
Syntax:
<script language="php">
// Your PHP code here
</script>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Script-Style PHP</title>
</head>
<body>
<p>
<script language="php">
echo "Hello, World!";
</script>
</p>
</body>
</html>
5. Echoing Content Directly:
You can also directly echo content from PHP within HTML, without enclosing it in
PHP tags.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Direct PHP Echo</title>
</head>
<body>
<p>
<?php echo "Hello, World!"; ?>
</p>
</body>
</html>
The choice of style largely depends on your preference and the structure of your web page.
The standard XML-style (<?php ?>) is the most common and widely used way to embed PHP
in web pages. Other styles are less common and may have limitations or affect the readability
and maintainability of your code.