Web Tech Notes
Web Tech Notes
UNIT I
Introducing PHP – Basic development Concepts – Creating first PHP Scripts – Using Variable and Operators
– Storing Data in variable – Understanding Data types – Setting and Checking variables Data types – Using
Constants – Manipulating Variables with Operators.
➢ Introduction to PHP :
PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential
background on the PHP language. It describes the nature and history of PHP, which platforms it runs on, and
how to configure it..
What does PHP do ?
PHP (Hypertext Preprocessor) is a versatile scripting language primarily used for web development, but it
can indeed be used in multiple ways. Here's a brief overview of the three primary ways PHP can be utilized :
1. Server-Side Scripting : Server-side scripting is the most common and traditional use of PHP. In this
context, PHP is embedded within HTML to create dynamic web pages. When a user requests a PHP page from
a web server, the server processes the PHP code, which may interact with databases, files, or other data sources,
and generates HTML content to be sent to the user's web browser.
2. Command-Line Scripting : PHP can also be used for command-line scripting, allowing developers to
create scripts that run on a server or a local computer without the need for a web server or browser. These
scripts can perform various tasks, such as data processing, file manipulation, and system administration.
3. Client-Side GUI Applications : While PHP is not commonly used for creating standalone client-side
graphical user interfaces (GUI), you can use PHP in combination with other technologies to develop client-
side web applications. PHP can generate HTML, CSS, and JavaScript code, which can be rendered in the
user's web browser. These applications can provide interactive and responsive user interfaces. While the bulk
of the processing still happens on the server side, JavaScript plays a more prominent role for client-side
interactivity.
➢ A Brief History of PHP :
PHP history dates back to the early days of the web, and it has gone through several significant milestones.
Here's a brief history of PHP :
1. Creation of PHP/FI (1994): PHP originated in 1994 when Rasmus Lerdorf, a programmer, created a
set of Perl scripts to track visits to his online resume. He later expanded it to handle form data and interact
with databases, naming it "Personal Home Page/Forms Interpreter" or PHP/FI. It was more of a collection of
tools than a programming language.
2. Introduction of PHP 2.0 (1995): PHP/FI was further developed, and in 1995, PHP 2.0 was released.
This version included more advanced features, better support for web forms, and could communicate with
various databases.
3. Birth of PHP 3.0 (1998): PHP 3.0, released in 1998, marked a significant milestone. It was a complete
rewrite of the PHP codebase and introduced the parser written in C, making it more efficient and faster. PHP
3.0 also added support for various databases and improved support for different web servers.
2
4. PHP 4.0 (2000): PHP 4.0, released in 2000, was a major step forward in PHP's evolution. It included
enhanced support for object-oriented programming (OOP), better performance, and added numerous features.
PHP was now recognized as a full-fledged scripting language suitable for building dynamic websites.
5. PHP 5.0 (2004): PHP 5.0, released in 2004, brought even more significant changes. It introduced the
Zend Engine 2, which greatly improved performance and added features like exception handling, and support
for OOP was significantly enhanced with the introduction of classes and interfaces.
6. PHP 5.3 (2009): PHP 5.3, released in 2009, included features such as namespaces and late static binding,
which made it easier to manage large codebases and improve code organization.
7. PHP 5.4 (2012): PHP 5.4, released in 2012, focused on performance improvements, and it introduced
short array syntax, traits, and improvements in syntax and language features.
8. PHP 7.0 (2015): PHP 7.0 was a ground-breaking release in terms of performance. It introduced the Zend
Engine 3, which significantly improved PHP's execution speed. The update also included scalar type
declarations, the spaceship operator, and the null coalescing operator.
9. PHP 7.4 (2019): PHP 7.4 brought features like arrow functions, typed properties, and improved
performance.
10. PHP 8.0 (2020): PHP 8.0 introduced several new features, including the JIT (Just-In-Time) compiler,
union types, and match expressions. It further enhanced performance and language capabilities.
PHP continues to evolve, with regular updates and improvements. It remains a widely used language for
web development, powering countless websites and web applications. Its open-source nature and active
community make it a versatile and robust choice for developers around the world.
➢ Installing PHP :
As was mentioned above, PHP is available for many operating systems and platforms. Therefore, we are
encouraged to go to this URL to find the environment that most closely fits the one we will be using and
follow the appropriate instructions. From time to time, we may also want to change the way PHP is configured.
To do that we will have to change the PHP configuration file and restart our Apache server. Each time we
make a change to PHP’s environment, we will have to restart the Apache server in order for those changes to
take effect. PHP’s configuration settings are maintained in a file called [Link]. The settings in this file control
the behaviour of PHP features, such as session handling and form processing.
➢ A Walk Through PHP :
PHP pages are generally HTML pages with PHP commands embedded in them.
Example 1-1. hello_world.php
<html>
<head>
<title> Look out World </title>
</head>
<body>
<?php echo “Hello, World!”; ?>
</body>
</html>
Save the contents of Example 1-1 to a file, hello_world.php, and point your browser to it. The PHP echo
command produces output (the string “Hello, world!” in this case) inserted into the HTML file. In this
example, the PHP code is placed between the tags.
➢ Procedure of Configure PHP on windows :
Configuring PHP on a Windows system involves several steps to set up the PHP interpreter and integrate it
with a web server like Apache or Nginx. Here is a step-by-step procedure to configure PHP on Windows:
3
1. Download PHP:
Visit the PHP official website ([Link] and download the latest stable version
of PHP for Windows. Choose the thread-safe version.2. Install PHP: Extract the downloaded PHP zip archive
to a directory on your system (e.g., C:\PHP).
3. Configure [Link]:
Inside the PHP directory, locate the [Link]-development file and make a copy of it named [Link]. This
is the configuration file for PHP. Open [Link] with a text editor and configure PHP settings according to
your needs. For example, you can set the time zone, enable extensions, and adjust memory limits. Be sure to
save the changes.
4. Add PHP to PATH (Optional but recommended) :
To use PHP from the command line globally, you can add the PHP directory to your system's PATH
environment variable. This step is optional but makes it easier to run PHP scripts from the command line.
5. Web Server Configuration:
If you don't have a web server installed, you can use the built-in web server provided by PHP for
development purposes by running php -S localhost:80 in the directory containing your PHP files. For a
production setup, you would typically use Apache or Nginx.
6. Configure Web Server:
If you're using Apache:
Download and install Apache from the official website ([Link]
Open the Apache [Link] file (usually located in the conf directory) and add the following
lines to load the PHP module :
LoadModule php_module "C:/PHP/php8apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/PHP"
If you're using Nginx, you'll need to configure FastCGI to work with PHP. This involves modifying your
Nginx configuration file to pass PHP requests to the FastCGI server. You'll also need to specify the PHP
interpreter's location.
7. Test PHP:
Create a simple PHP script (e.g., [Link]) and place it in your web server's document root (e.g., htdocs
for Apache).
In the PHP script, you can use the phpinfo() function to display PHP information.
For Example:
<?php
phpinfo();
?>Access the script in your web browser (e.g., [Link] to check if PHP is configured correctly.
8. Troubleshooting:
If you encounter any issues, check the error logs of both PHP and your web server for details. Once you
have successfully configured PHP on Windows, you can start developing and running PHP web applications.
Be sure to keep PHP and your web server software up to date for security and performance reasons.
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:
4
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.
// This is a single-line comment
/*
This is a multi-line comment that
spans multiple lines
*/
5. Shell Style Comments :
In PHP, shell-style comments begin with # and extend to the end of the line. They are similar to single-line
comments that start with // or /* ... */ comments, but they are less common in PHP and may not be as widely
recognized or supported as // or /* ... */ comments. Here's an example of shell-style comments in PHP:
##########################################
####### This is a shell-style comment ##########
$variable = 42;
#########################################
➢ Literals :
In PHP, a literal is a notation used to represent fixed values in source code. These values are constant and don't
change during the execution of the program. PHP supports various types of literals to represent different data
types, such as integers, floating-point numbers, strings, and more.
Example : 2001 , 1.34 , “Hello World” , ‘Hi’ , true , null
5
➢ Identifiers :
In PHP, identifiers are names used to represent variables, functions, classes, and constants. Identifiers follow
specific rules and conventions, and it's important to use meaningful and consistent names in your code. Here
are the rules for creating identifiers for variable names, function names, class names, and constants
1. Variable Names :
Variable names are used to store and manipulate data in PHP. They must start with a dollar sign ($)
followed by a letter or an underscore, and can be followed by letters, numbers, and [Link] names
are case-sensitive.
Example of valid variable names:
$count;
$user_name;
$_value;
$myVariable123;
2. Function Names :
Function names in PHP are not case-sensitive, which means you can call them with different letter casing,
but it's a good practice to use lowercase letters for function names.
Function names must start with a letter or an underscore, followed by letters, numbers, and underscores.
Example of valid function
names myFunction();
process_data(); _helperFunction();
3. Class Names :
Class names in PHP are typically written in CamelCase, where the first letter of each word is capitalized,
and there are no underscores. Class names are case-sensitive.
Example of valid class names:
class MyClass {} class
UserRegistration {} class
DatabaseConnection {}
4. Constants:
Constants in PHP are typically written in uppercase letters with underscores separating words. By
convention, they are often defined at the top of a script or in a configuration file.
Constants are case-sensitive.
Example of valid constants:
define('PI', 3.14159);
define('DB_HOST',
'localhost');
define('MAX_USERS', 100);
It's important to note that PHP is case-sensitive when it comes to variable names and class names but not for
function names. Therefore, you must use the correct letter casing when referencing variables and class
[Link], meaningful and descriptive names should be used for all identifiers to improve code
readability and maintainability. Using consistent naming conventions, such as camelCase for variables and
functions and StudlyCase for classes, can make your code more organized and easier to understand.
➢ Keywords :
Keywords in PHP are reserved words that have special meanings and purposes within the PHP language. These
words cannot be used as identifiers (e.g., variable names, function names, class names) because they are
6
predefined and serve specific roles in the language. Here is a list of some of the most common keywords in
PHP :
1. Basic Keywords:
Echo : Used to output data to the browser. print : Similar to echo, used to output data. return: Used
to return a value from a function. include: Used to include and evaluate a specified file. require:
Used to include and evaluate a specified file, and it's considered fatal if the file is not found.
include_once: Similar to include, but ensures the file is included only once. require_once: Similar
to require, but ensures the file is included only once.
2. Control Structures:
if: Used to conditionally execute code. else: Used in conjunction with if to
execute code when the condition is false. elseif or else if: Used to add additional
conditions in an if statement. while: Used to create a loop that executes code
while a condition is true. for: Used to create a loop with a specific initialization,
condition, and increment. foreach: Used to loop through arrays and objects.
switch: Used to create a switch statement for multiple condition checks. case:
Used within a switch statement to specify different cases. break: Used to exit a
loop or a switch statement.
continue: Used to skip the current iteration of a loop.
3. Data Types:
int, integer: Used to represent integer data types. float, double:
Used to represent floating-point (decimal) data types. string: Used
to represent string data types. bool, boolean: Used to represent
Boolean data types. array: Used to represent arrays. object: Used
to represent objects.
null: Used to represent the absence of a value.
4. Classes and Objects:
class: Used to define a class. new: Used to create an instance of a class. this: Used to refer to
the current object within a class. public, private, protected: Used to specify the visibility of class
members (properties and methods).
static: Used to define static methods and properties within a class.
5. Error Handling:
try: Marks the beginning of a block of code to be tested for
exceptions. catch: Handles exceptions that are thrown within a try
block. throw: Throws an exception within a block of code.
finally: Marks a block of code that is always executed, whether an exception is thrown or not.
6. Namespaces:
namespace: Used to declare a namespace.
use: Used to import classes or functions from a namespace.
7. Other Keywords:
global: Used to access a global variable from within a
function. const: Used to define class constants. define: Used
to define global constants.
include_once, require_once: Used to include files only once.
7
These are some of the most commonly used keywords in PHP. It's important to understand their meanings and
how they are used in PHP programming to write effective and efficient code.
➢ Data Types :
PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point
numbers, strings, and Booleans. Two are compound (collection) types: arrays and objects. The remaining two
are special types: resource and NULL.
In PHP, single value data types or scalar data types represent individual values, as opposed to compound data
types like arrays or objects. PHP has several scalar data types, each of which can hold a single value. Here are
the main scalar data types in PHP :
1. Integer (int):
The integer data type represents whole numbers, both positive and negative, without a fractional or decimal
component. Examples of integers include -42, 0, and 100.
$age = 30; // an integer variable
2. Floating-Point (float or double):
Floating-point data types represent numbers with a decimal point or in scientific notation. Examples
include 3.14159, -0.01, and 2.5e3.
$pi = 3.14159; // a floating-point variable
3. String:
The string data type represents sequences of characters, such as text. Strings can be enclosed in single
quotes (') or double quotes (").
$name = "John"; // a string variable
4. Boolean (bool):
Boolean data types represent one of two possible values: true or false. Booleans are often used for
conditional statements and comparisons.
$isMember = true; // a boolean variable
In PHP, arrays and objects are compound data types used to store collections of values. They are not scalar
data types because they can hold multiple values, including other data types. Here's an overview of arrays and
objects in PHP :
1. Arrays:
Arrays are ordered collections of values that can be of various data types, including scalars, other arrays,
and objects. They are versatile and commonly used for storing and manipulating multiple pieces of data. In
PHP, there are three main types of arrays:
Indexed Arrays: These use numeric indices (0, 1, 2, etc.) to access elements.
Associative Arrays: These use named keys to access elements (key-value pairs).
Multidimensional Arrays: These are arrays of arrays, allowing you to create complex data structures.
Example of an indexed array :
$fruits = ['apple', 'banana', 'cherry'];
Example of an associative array:
$person = ['first_name' => 'John', 'last_name' => 'Doe', 'age' => 30]; Example
of a multidimensional array :
$matrix = [
[1, 2, 3],
[4, 5, 6],
8
[7, 8, 9]];
2. Objects:
Objects are instances of classes and are used to model complex, structured data. They can contain properties
(variables) and methods (functions). Objects are integral to object-oriented programming (OOP) in PHP.
9
To create an object, you define a class and then instantiate it using the new keyword. You can access object
properties and methods using the arrow operator (->).
Example of defining a class and creating an object:
class Person { public $name; public
function sayHello() { echo "Hello, my
name is " . $this->name;
}
}
$person = new Person();
$person->name = "John";
Example of accessing an object's property and calling a method :
$person->sayHello();
// Output: Hello, my name is John
1. Resource:
The resource data type represents a special type of variable that holds a reference to an external resource,
such as a database connection, file handle, or socket. Resources are typically created and manipulated by
various PHP extensions or functions that interact with external systems.
Resources are not typically used for general data storage but are important for managing external resources
and connections.
For example, when working with a database, you might obtain a resource representing the database connection.
Example of working with a resource (database connection):
$db = mysqli_connect("localhost", "username", "password", "database"); //
$db is a resource representing the database connection
2. NULL :
The NULL data type represents the absence of a value. It is often used to indicate that a variable has not
been assigned a value or that a variable should be reset to an undefined state.
It's important to note that NULL is not the same as an empty string, zero, or false. It is a distinct data type
in PHP.
Example of using NULL:$variable = null; // Assigning a variable the value of NULL
Example of checking for NULL:
if ($variable === null) { echo
"The variable is NULL.";
}
These two special data types, resource and NULL, serve unique purposes in PHP. resource is used to manage
external resources, while NULL is used to indicate the absence of a value. Understanding them roles and when
to use them is essential in PHP programming.
➢ Variables :
In PHP, variables are used to store and manipulate data. They have various characteristics, including variable
variables, variable references, and variable scope. Let's explore these concepts:
1. Variables in PHP:
Variables are used to store data, such as numbers, strings, and objects.
Variable names must start with a dollar sign ($) followed by a letter or underscore, and can contain letters,
numbers, and underscores. Variable names are case-sensitive in PHP.
Example:
$name = "John";
// A variable storing a string
10
$age = 30;
// A variable storing an integer
2. Variable Variables:
PHP allows you to use a variable's value as the name of another variable. This is called "variable variables."
You use a double dollar sign ($$) to indicate a variable variable.
Example:
$variableName = "age";
$$variableName = 25; // Creates a variable $age with a value of 25
3. Variable References:
PHP supports variable references, which allow multiple variables to refer to the same data in memory.
This is useful when you want to manipulate the same value in different parts of your code. You
use the ampersand (&) symbol to create a reference.
Example:
$original = 10;
$reference = &$original;
// $reference and $original now refer to the same data
$reference = 20;
// Changes both $reference and $original to 20
4. Variable Scope:
Variable scope defines where a variable can be accessed within your code. PHP has three main types of
variable scope:
Local Variables:
Local variables are declared inside a function or method and are only accessible within that function. They
do not exist outside the function's scope.
Example:
function myFunction() {
$localVariable = "Local variable"; }
Global Variables:
Global variables are declared outside of any function and can be accessed from anywhere in the script. You
need to use the global keyword inside a function to modify a global variable.
Example:
$globalVariable = "Global variable";
function myFunction() { global
$globalVariable;
$globalVariable = "Modified global variable"; }
Static Variables:
Static variables are local variables that retain their values between function calls. They are initialized only
once when the function is first called.
Example:
function countCalls() { static
$count = 0;
$count++;
11
Example:
$difference = 10 - 4;
// $difference is 6
3. Multiplication (*):
Example:
$product = 6 * 7;
// $product is 42
4. Division (/):
Example:
$quotient = 18 / 3;
// $quotient is 6
5. Modulus (%):
Example:
$remainder = 10 % 3;
// $remainder is 1 (10 divided by 3 leaves a remainder of 1)
6. Exponentiation ()**:
Raises one numeric value to the power of another. Example:
$result = 2 ** 3;
// $result is 8 (2 raised to the power of 3)
These arithmetic operators are used extensively in PHP for performing various mathematical calculations,
including basic arithmetic, power calculations, and finding remainders. You can combine these operators to
create complex expressions for more advanced calculations.
2. Strings Concatenation Operator :
The string concatenation operator in PHP is a period (.) that is used to combine or concatenate two or more
strings together. This operator allows you to join multiple strings to create a single, longer string. Here's
how it works:
$string1 = "Hello, ";
$string2 = "world!";
13
7. Logical Operator :
Logical operators in PHP are used to combine or modify the logical values (true or false) of expressions or
conditions. These operators are fundamental for controlling the flow of a program by evaluating conditions
and making decisions based on the results of these logical evaluations. PHP provides the following logical
operators:
1. Logical AND (&& and and) Operator:
The logical AND operator returns true if both expressions on its left and right sides are true. Otherwise, it
returns false. Example:
$a = true;
$b = false;
$result = $a && $b; // $result is false
2. Logical OR (|| and or) Operator:
The logical OR operator returns true if at least one of the expressions on its left or right side is true. It returns
false only if both expressions are false.
Example:
$a = true;
$b = false;
$result = $a || $b; // $result is true
3. Logical NOT (! and not) Operator:
The logical NOT operator is a unary operator that negates the logical value of an expression. If the
expression is true, it returns false; if the expression is false, it returns true. Example:
$a = true;
$result = !$a; // $result is false4.
4. Logical XOR (xor ) Operator:
The logical XOR (exclusive OR) operator returns true if exactly one of the expressions on its left or right
side is true. It returns false if both expressions are true or both are false.
Example:
$a = true;
$b = false;
16
In PHP, assignment operators are used to assign values to variables. These operators allow you to store data
in variables for later use. PHP provides a variety of assignment operators for different scenarios. Here are
some of the common assignment operators:
1. Assignment Operator (=):
The basic assignment operator is used to assign a value to a variable.
Example:
$x = 5; // $x now contains the value 5
2. Addition Assignment Operator (+=):
Adds a value to the variable and assigns the result to the variable. Example:
$y = 10;
$y += 3; // $y is now 13 (10 + 3)
3. Subtraction Assignment Operator (-=):
Subtracts a value from the variable and assigns the result to the variable. Example:$z
= 15;
$z -= 7; // $z is now 8 (15 - 7)
4. Multiplication Assignment Operator (*=):
Multiplies the variable by a value and assigns the result to the variable. Example:
$w = 4;
$w *= 6; // $w is now 24 (4 * 6)
5. Division Assignment Operator (/=):
Divides the variable by a value and assigns the result to the variable. Example:
$v = 20;
$v /= 5; // $v is now 4 (20 / 5)
6. Modulus Assignment Operator (%=):
Performs the modulus operation on the variable and assigns the result to the variable. Example:
$u = 12;
$u %= 5; // $u is now 2 (12 % 5)
7. Concatenation Assignment Operator (.=):
Concatenates a string to the variable's existing value and assigns the result to the variable. Example:
$text = "Hello";
$text .= ", World!"; // $text is now "Hello, World!"
These assignment operators are used extensively in PHP to manipulate variables by performing operations and
storing results.
10. Assignment Operator :
In PHP, there are several miscellaneous operators that serve various purposes beyond arithmetic, comparison,
and assignment operations. These operators are used in specific situations and can be quite handy in certain
scenarios. Here are some of the miscellaneous operators in PHP:
1. Ternary Conditional Operator (? :):
The ternary operator is a shorthand way of expressing conditional statements. It allows you to return one
of two values depending on the result of a condition.
Syntax: $condition ? $value_if_true : $value_if_false
Example:
$age = 25;
$message = ($age >= 18) ? "You are an adult" : "You are a minor";
2. Null Coalescing Operator (??) (PHP 7.0 and later):
18
The null coalescing operator is used to provide a default value for a variable or expression when the original
value is null.
Syntax: $value ?? $default_value
Example:
$username = $_GET['user'] ?? "Guest";
3. Error Control Operator (@):
The error control operator suppresses error messages generated by PHP. It's used to prevent error messages
from being displayed to the user.
Example:
$result = @file_get_contents('[Link]');
4. Execution Operator (backticks or shell_exec):
The execution operator allows you to run shell commands and capture the output of those commands in a
PHP variable.
Example:
$output = `ls -l`;
5. Concatenation Operator (.):
As mentioned earlier, the concatenation operator is used to join two or more strings together. Example:
$str1 = "Hello, ";
$str2 = "world!";
$combinedString = $str1 . $str2;
6. Instanceof Operator:
The instanceof operator is used to check if an object is an instance of a particular class.
Example:
if ($object instanceof MyClass) {
// Do something if $object is an instance of MyClass }
7. Type Operators (is_array, is_string, is_numeric, etc.):
PHP provides a set of type operators that can be used to check the type of a variable or value.
Example:
if (is_array($variable)) {
// Check if $variable is an array
}
These miscellaneous operators extend the functionality of PHP and help you accomplish specific tasks or
handle edge cases in your code. It's important to use themeffectively and consider their implications when
designing your applications.
UNIT II
Controlling Program Flow: Writing Simple Conditional Statements - Writing More ComplexConditional
Statements – Repeating Action with Loops – Working with String and NumericFunctions ➢ Flow Control
Statements :
Flow control statements in PHP are used to determine the order in which a program's instructions are executed.
They allow you to create decision-making structures, loops, exception handling, and more. Below are
examples of various flow control statements in PHP, including their syntax and usage.
1. if Statement:
The if statement is used for conditional execution. It runs a block of code if a specified condition is true.
19
Syntax :
if (condition) {
// Code to execute when the condition is true
} elseif (another_condition) {
// Code to execute when another condition is true
} else {
// Code to execute when none of the conditions are true }
Example : $score
= 85; if ($score >=
90) { echo "A
grade";
} elseif ($score >= 80) { echo
"B grade";
} else { echo "C
grade";
}
2. switch Statement:
The switch statement is used to select one of many code blocks to be executed.
Example:
Syntax :
switch (expression) { case
value1:
// Code to execute when expression equals
value1 break; case value2:
// Code to execute when expression equals value2 break;
// Additional cases... default:
// Code to execute when no case matches}
Example : $day =
"Monday"; switch
($day) { case
"Monday":
echo "It's the start of the week.";
break; case "Friday": echo
"TGIF!"; break; default:
echo "Enjoy your day.";
}
3. while Loop:
The while loop repeatedly executes a block of code as long as a specified condition is true.
Syntax :
while (condition) {
// Code to execute as long as the condition is true }
Example : $count = 1;
while ($count <= 5) { echo
"Count: $count<br>";
$count++;
}
20
4. for Loop:
The for loop is used to iterate a specific number of times.
Syntax :
for (initialization; condition; increment) {
// Code to execute as long as the condition is true }
Example:
for ($i = 1; $i <= 5; $i++) {
echo "Iteration $i<br>";
}5. foreach Loop:
The foreach loop is used to iterate over elements in an array or other iterable objects.
Syntax :
foreach ($array as $value) {
// Code to execute for each element in the array }
Example :
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) { echo "I like
$fruit<br>";
}
Functions :
PHP Functions
A function is a block of code that performs a specific task and can be reused multiple times.
✅ Math Functions:
Function Description Example
✅ Date/Time Functions:
Function Description Example
✅ Array Functions:
UNIT III
Working with Arrays: Storing Data in Arrays – Processing Arrays with Loops and Iterations –Using Arrays
with Forms - Working with Array Functions – Working with Dates and Times.
Arrays:
Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single
variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays.
Understanding how to use arrays in PHP is important for working with data efficiently.
• PHP offers many built-in array functions for sorting, merging, searching, and more.
• PHP Arrays can store values of different types (e.g., strings, integers, objects, or even other arrays) in the
same array.
• They are dynamically sized.
• They allow you to store multiple values in a single variable, making it easier to manage related data.
Types of Arrays in PHP
There are three main types of arrays in PHP:
1. Indexed Arrays
Indexed arrays use numeric indexes starting from 0. These arrays are ideal when you need to store a list of
items where the order matters.
<?php
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
?>
Output
22
apple
2. Associative Arrays
Associative arrays use named keys, which are useful when you want to store data with meaningful identifiers
instead of numeric indexes.
<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York"); echo
$person["name"];
?>
Output
GFG
3. Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as elements. These are used to represent more
complex data structures, such as matrices or tables.
<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"GFG" => array("age" => 22, "grade" => "B")
);
echo $students["GFG"]["age"];
?>
Output
22
Creating Array in PHP
In PHP, arrays can be created using two main methods:
1. Using the array() function
The traditional way of creating an array is using the array() function.
$fruits = array("apple", "banana", "cherry");
2. Using short array syntax ([])
In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
$fruits = ["apple", "banana", "cherry"];
You can also create associative arrays by specifying custom keys:
$person = ["name" => "GFG", "age" => 30];
Accessing and Modifying Array Elements
1. Accessing Array Elements
You can access individual elements in an array using their index (for indexed arrays) or key (for associative
arrays).
23
Array Iteration
You can loop through arrays using loops such as foreach or for.
• Using foreach Loop:
$fruits = ["Apple", as "Banana", "Cherry"];
foreach ($fruits $fruit) {
echo $fruit . "<br>";
}
• Using for Loop:
$numbers ($i = = [1, < 2, 3, $i++) 4];
for 0; $i count($numbers); {
echo $numbers[$i] . "<br>";
}
Output
2025-04-04
In this example:
• Y stands for the four-digit year.
• m represents the two-digit month.
• d represents the two-digit day.
Example 2: Display Current Date and Time
<?php echo date("Y-m-d
H:i:s");
?>
Output
2025-04-04 12:34:11
In this example:
• H represents hours in 24-hour format.
• i represents minutes.
• s represents seconds.
Date Formatting in date() function
The format parameter of the date() function is a string that can contain multiple characters, allowing to generate
the dates in various formats. Date-related formatting characters that are commonly used in the format string:
• d: Represents the day of the month, two digits with leading zeros (01 or 31).
• D: Represents the day of the week in the text as an abbreviation (Mon to Sun).
• m: Represents month in numbers with leading zeros (01 or 12).
• M: Represents month in text, abbreviated (Jan to Dec).
• y: Represents the year in two digits (08 or 14).
• Y: Represents the year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or
spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
26
Output
Output
1743772332
April 04, 2025 01:12:12 PM
Get Your Time Zone
In PHP, you can easily get the current time zone using the date_default_timezone_get() function. This function
returns the default time zone set in your PHP configuration or the time zone that has been explicitly set within
your script using date_default_timezone_set().
Syntax:
date_default_timezone_get();
27
<?php
date_default_timezone_set("America/New_York")
; echo "The time is " . date("h:i:sa"); ?>
Output
The time is 01:26:09pm
🔸 Convert to Date:
php
CopyEdit
echo date("Y-m-d", strtotime("next Monday"));
UNIT IV
Using Functions and Classes: Creating User-Defined Functions - Creating Classes – UsingAdvanced OOP
Concepts. Working with Files and Directories: Reading FilesWriting FilesProcessing Directories
🔹 2. User-defined Functions
A function in PHP is a self-contained block of code that performs a specific task. It can accept inputs
(parameters), execute a set of statements, and optionally return a value.
• PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.
• Functions can accept parameters and return values, enabling dynamic behavior based on inputs.
• PHP supports both built-in functions and user-defined functions, enhancing flexibility and modularity in
code.
Creating a Function in PHP
A function is declared by using the function keyword, followed by the name of the function, parentheses
(possibly containing parameters), and a block of code enclosed in curly braces.
Syntax
function functionName($param1, $param2) {
// Code to be executed
return $result; // optional
}
In this syntax:
• function is a keyword that starts the function declaration.
• functionName is the name of the function.
• $param1 and $param2 are parameters (optional) that can be passed to the function.
• The return statement (optional) sends a value back to the caller.
28
Output
8
In this example:
• The function sum() is defined to take two parameters, $a and $b, and return their sum.
• The function is called with 5 and 3 as arguments, and it returns the result, which is 8.
Types of Functions in PHP PHP
has two types of functions:
1. User-Defined Functions
A user-defined function is created to perform a specific task as per the developer's need. These functions can
accept parameters, perform computations, and return results.
Now, let us understand with the help of example:
<?php function
addNumbers($a, $b) { return
$a + $b;
} echo addNumbers(5, 3); // Output:
8 ?>
Output
8
In this example:
• The function addNumbers is defined by the user to take two parameters, $a and $b, and returns their sum
($a + $b).
• The function is called with 5 and 3 as arguments, so it adds these numbers together.
2. Built-in Functions
PHP comes with many built-in functions that can be directly used in your code. For example, strlen(), substr(),
array_merge(), date() and etc are built-in PHP functions. These functions provide useful functionalities, such
as string manipulation, date handling, and array operations, without the need to write complex logic from
scratch.
<?php
$str = "Hello, World!"; echo
strlen($str); // Output: 13
?>
Output
29
13
In this example:
• A string variable $str is defined with the value "Hello, World!".
• The strlen() function is the built-in function in PHP that is used to calculate the length of the string $str.
PHP Function Parameters and Arguments
Functions can accept input values, known as parameters or arguments.
• Parameters are variables defined in the function declaration that accept values.
• Arguments are the actual values passed to the function when it is called. These values can be passed to the
function in two ways:
1. Passing by Value
When you pass a value by reference, the function works with a copy of the argument. This means the original
value remains unchanged.
<?php function add($x,
$y) { $x = $x + $y;
return $x;
}
Output
5
In this example:
• The function add() is defined with parameters $x and $y.
• The function adds $x and $y and returns the sum.
• The function is called with values 2 and 3, and the result 5 is printed.
2. Passing by Reference
By passing an argument by reference, any changes made inside the function will affect the original variable
outside the function.
<?php function
addByRef(&$x, $y) { $x = $x
+ $y;
}
$a = 5; addByRef($a,
3); echo $a; //
Outputs: 8
?>
Output
8
In this example:
30
Output
20
In this example:
• The function multiply() is defined to return the product of $a and $b.
• The function is called with 4 and 5 as arguments.
• The result 20 is returned and printed using echo.
Anonymous Functions (Closures)
PHP supports anonymous functions, also known as closures. These functions do not have a name and are often
used for passing functions as arguments to other functions.
<?php
$greet = function($name) { echo
"Hello, " . $name . "!";
};
$greet("GFG");
?>
Output
Hello, GFG!
In this example:
• An anonymous function is defined and assigned to the variable $greet.
• The function takes $name as a parameter and prints a greeting message.
• The function is called with the argument "GFG", and the greeting "Hello, GFG" is printed.
Recursion in PHP
Recursion is a process in which a function calls itself. It is often used in situations where a task can be broken
down into smaller, similar tasks.
<?php function
factorial($n) { if ($n
== 0) { return 1;
31
} else { return $n *
factorial($n - 1); } } echo
factorial(5);
?>
Output
120
In this example:
• The function factorial() is defined to calculate the factorial of a number $n using recursion.
• If $n is 0, the function returns 1 (base case); otherwise, it calls itself with $n - 1.
• When factorial(5) is called, the function recursively multiplies 5 * 4 * 3 * 2 * 1, returning 120.
Common PHP Functions
Here are some common PHP functions you should know:
1. String Functions
• strlen(): Returns the length of a string.
• strtoupper(): Converts a string to uppercase.
• strtolower(): Converts a string to lowercase.
• substr(): Returns a part of a string.
2. Array Functions
• array_push(): Adds elements to the end of an array.
• array_pop(): Removes the last element of an array.
• array_merge(): Merges two or more arrays.
3. Date and Time Functions
• date(): Returns the current date or time.
• strtotime(): Converts a string into a Unix timestamp.
• time(): Returns the current Unix timestamp.
[III ] Variable Scope:
In PHP, variables used inside functions have different scopes, which determine where and how those variables
can be accessed. There are primarily two types of variable scopes in PHP functions: local and global.
1. Local Scope (Function Scope):
• Variables defined within a function are said to have local scope.
• Local variables are only accessible within the function in which they are defined.
• They are not accessible outside of the function.
Example of local scope :
function myFunction() {
$localVariable = "I am local!";
echo $localVariable;
}
myFunction();
// Output: I am local!
echo $localVariable; // This will result in an error because $localVariable is not defined in the global scope.
2. Global Scope:
• Variables defined outside of all functions are said to have global scope.
• Global variables can be accessed from anywhere in the script, including inside functions.
32
• To access a global variable within a function, We need to use the global keyword or the
$GLOBALS superglobal. Example of global scope with global keyword :
$globalVariable = "I am global!"; function
myFunction() { global $globalVariable; // Access the
global variable echo $globalVariable; }
A class defines the structure of an object. It contains properties (variables) and methods (functions). These
properties and methods define the behavior and characteristics of an object created from the class.
Syntax:
<?php
class Camera {
// code goes here...
}
?>
<?php
class GeeksforGeeks
{ // Constructor public function construct(){ echo
'The class "' . CLASS . '" was initiated!';
}
}
// Create a new object
$obj = new GeeksforGeeks;
?>
Output
The class "GeeksforGeeks" was initiated!
In this example:
• The code defines a Car class with two properties: color and model.
• The construct method initializes the properties when a new Car object is created.
• The displayDetails method prints the car's model and color.
• A new Car object is created using new Car("Red", "Toyota"), passing values for color and model.
• The displayDetails method is called on the $myCar object to display the car's details.
Creating Objects from Classes
Once a class is defined, you can create objects based on it. Here's how you can create an object from a class:
$object = new ClassName('Hello', 'World');
echo $object->method1(); // Outputs: Hello World
In this example:
• new ClassName() creates an instance (object) of the class ClassName.
• The constructor is called with the parameters 'Hello' and 'World', which are passed to initialize the object's
properties.
• The method method1 is called on the object to display the concatenated properties.
A class defines the structure of an object. It contains properties (variables) and methods (functions). These
properties and methods define the behavior and characteristics of an object created from the class.
33
Syntax:
<?php
class Camera {
// code goes here...
}
?>
<?php
class GeeksforGeeks
{
// Constructor public function construct(){ echo
'The class "' . CLASS . '" was initiated!'; }
}
// Create a new object
$obj = new GeeksforGeeks;
?>
Output
The class "GeeksforGeeks" was initiated!
PHP File Handling
In PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a
file, creating new files, or deleting existing ones. File handling is essential for applications that require the
storage and retrieval of data, such as logging systems, user-generated content, or file uploads.
Types of File Operations in PHP
Several types of file operations can be performed in PHP:
• Reading Files: PHP allows you to read data from files either entirely or line by line.
• Writing to Files: You can write data to a file, either overwriting existing content or appending to the end.
• File Metadata: PHP allows you to gather information about files, such as their size, type, and last modified
time.
• File Uploading: PHP can handle file uploads via forms, enabling users to submit files to the server.
Common File Handling Functions in PHP
• fopen() - Opens a file
• fclose() - Closes a file
• fread() - Reads data from a file
• fwrite() - Writes data to a file
• file_exists() - Checks if a file exists
• unlink() - Deletes a file
Opening and Closing Files
Before you can read or write to a file, you need to open it using the fopen() function, which returns a file
pointer resource. Once you're done working with the file, you should close it using fclose() to free up resources.
34
<?php
Writing to Files
35
You can write to files using the fwrite() function. It writes data to an open file in the specified mode.
<?php
// Open the file in write
mode $file = fopen("[Link]",
'w'); if ($file) {
$text = "Hello world\n";
fwrite($file, $text);
fclose($file);
}?>
Deleting Files
Use the unlink() function to delete the file in PHP.
<?php
UNIT V
Working with Database and SQL : Introducing Database and SQL- Using MySQLAdding andmodifying Data-
Handling Errors – Using SQLite Extension and PDO Extension. IntroductionXML - Simple XML and DOM
Extension SQL:
"localhost/phpmyadmin"
Steps in Detail:
• Open XAMPP and start running Apache, MySQL and FileZilla
36
• Now open your PHP file and write your PHP code to create database and a table in your database.
PHP code to create a database:
<?php
In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns
and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number
of columns, but can have any number of rows.
To connect to an existing database, we can pass an extra variable "database name" while connecting to MySQL.
The CREATE TABLE statement is used to create a table in MySQL.
The data types that will be used are :
1. VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The
maximum size is specified in parenthesis.
2. INT :he INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer
value between -2147483648 to 2147483647.
The attributes that are used along with data types in this article are:
1. NOT NULL: Each row must contain a value for that column, null values are not allowed.
2. PRIMARY KEY: Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting
is often an ID number.
Creating tables in three different versions are described below:
PDO in PHP :
There are three main options for creating to a MySQL database server.
• MySQLi procedural
• MySQLi object-oriented
• PDO (PHP Data Objects )
MySQLi procedural and MySQLi object-oriented only support MySQL database but PDO is an advanced
method along with MySQL which supports Postgres, SQLite, Oracle, and MS SQL Server.
PDO is more secure than the first two options and it is also faster in comparison with MySQLi procedural and
MySQLi object-oriented.
PDO is a database access layer that provides a fast and consistent interface for accessing and managing
databases in PHP applications. Every DBMS has a specific PDO driver that must be installed when you are
using PDO in PHP applications.
It simplifies the database operations including:
• Creating database connection
• Executing queries
• Handling errors
• Closing the database connections
When we want to connect PHP and MySQL then we need to follow 3 steps:
• Connection with the database
• Run SQL Query
• Closing the database connection Steps for connection using PDO.
Connection:
In this step, we connect with the database
Note: The prepare() method is more secure than the query() method.
Close the connection:
For closing the database connection using PDO.
$conn = null;
Parameters: It contains the following parameters.
40
Output:
Error : SQLSTATE[28000] [1045]
Access denied for user 'roott'@'localhost'
(using password: NO)
Example 1: Suppose we have a database "gfg" with a table "students". We want to fetch the details like
"id" and name of all the students present in the table "students".
<?php
$dsn = "mysql:host=localhost;dbname=gfg";
$user = "root";
$passwd = "";
4 Student4
Benefits of PDO:
• Usability: PDO contains helper functions to operate automatic routine operations.
• Reusability: We can access multiple databases because it offers a unified API.
• Security: It provides protection from SQL injection because it uses a prepared statement. A prepared
statement separates the instruction of the SQL statement from the data.
• Error handling: It uses exceptions for error handling. There are three types of modes:
Silent ,Warning ,Exception
• Multiple database support: It is used to access any database which is written for the PDP driver. We need
to find a suitable driver and add them when we use them. There are several PDO drivers available like
Microsoft SQL Server, Sybase, PostgreSQL, and many more.
XML | Basics
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents
in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity,
generality, and usability across the Internet. It is a textual data format with strong support via Unicode for
different human languages. Although the design of XML focuses on documents, the language is widely used
for the representation of arbitrary data structures such as those used in web services.
1. XML stands for extensible Markup Language
2. XML is a markup language like HTML
3. XML is designed to store and transport data
4. XML is designed to be self-descriptive
Differences between XML and HTML
XML and HTML were designed with different goals:
• XML is designed to carry data emphasizing on what type of data it is. • HTML is designed to
display data emphasizing on how data looks
• XML tags are not predefined like HTML tags.
• HTML is a markup language whereas XML provides a framework for defining markup languages.
• HTML is about displaying data,hence it is static whereas XML is about carrying information,which makes
it dynamic.
DOM:
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and
content of a document on the web.
The DOMDocument::createElement() function is an inbuilt function in PHP which is used to create a new
instance of class DOMElement. Syntax:
DOMElement DOMDocument::createElement( string $name, string $value )
Parameters: This function accepts two parameters as mentioned above and described below:
• $name: This parameter holds the tag name of the element.
• $value: This parameter holds the value of the element. The default value of this function creates an empty
element. The value of element can be set later using DOMElement::$nodeValue.
Return Value: This function returns a new instance of class DOMElement on success or FALSE on failure.
Below programs illustrate the DOMDocument::createElement() function in PHP: Program 1: <?php
?>
Output:
<?xml version="1.0" encoding="iso-8859-1"?>
<organization>GeeksforGeeks</organization>