0% found this document useful (0 votes)
22 views87 pages

Server Side Processing and Scripting

PHP (Hypertext Preprocessor) is an open-source server-side scripting language used for web development, allowing for dynamic web pages and database interactions. It is easy to learn, cross-platform compatible, and supports various programming paradigms, making it popular for creating web applications and content management systems. Key features include database connectivity, session management, and a syntax similar to C, with variables being loosely typed and case-sensitive.

Uploaded by

Deshma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views87 pages

Server Side Processing and Scripting

PHP (Hypertext Preprocessor) is an open-source server-side scripting language used for web development, allowing for dynamic web pages and database interactions. It is easy to learn, cross-platform compatible, and supports various programming paradigms, making it popular for creating web applications and content management systems. Key features include database connectivity, session management, and a syntax similar to C, with variables being loosely typed and case-sensitive.

Uploaded by

Deshma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

UNIT 4 SERVER SIDE PROCESSING

AND SCRIPTING - NOTES

What is PHP?
1. PHP (Hypertext Preprocessor) is an open-source server-side
scripting language primarily used for web development. PHP can be
embedded into HTML code.
2. PHP is mainly used for server-side scripting, which runs scripts on
the web server and then forwards the HTML they process to the web
browser on the client. This makes it possible for programmers to
design dynamic web pages that can manage sessions, handle forms,
communicate with databases, and carry out a variety of other duties
necessary for online applications.
3. It was developed by Rasmus Lerdorf in 1994. PHP is a a recursive
acronym for 'PHP: Hypertext Preprocessor'.
4. PHP is the world's most popular server-side programming language.
Its latest version is PHP 8.4.3, released on January 16 th, 2025.
5. PHP is a server-side scripting language that is embedded in HTML.
PHP is a cross-platform language, capable of running on all major
operating system platforms and with most of the web server
programs such as Apache, IIS, lighttpd and nginx.
6. A large number of reusable classes and libraries are available on
PEAR and Composer. PEAR (PHP Extension and Application
Repository) is a distribution system for reusable PHP libraries or
classes. Composer is a dependency management tool in PHP.
7. PHP is one of the most preferred languages for creating interactive
websites and web applications. PHP scripts can be easily embedded
into HTML. With PHP, you can build
8. Web Pages and Web-Based Applications
9. Content Management Systems, and
10. E-commerce Applications etc.
11. A number of PHP based web frameworks have been developed
to speed-up web application development. The examples are
WordPress, Laravel, Symfony etc.

PHP Characteristics
Below are the main characteristics which make PHP a very good choice for
web development −

1. PHP is Easy to Learn


2. Open-Source & Free
3. Cross-Platform Compatibility
4. Server-Side Scripting
5. Embedded in HTML
6. Database Connectivity
7. Object-Oriented & Procedural Support
8. Large Standard Library
9. Supports Various Protocols
10. Framework Support

Advantages of Using PHP


1. PHP is a multi-paradigm language that supports imperative,
functional, object-oriented, and procedural programming
methodologies.
2. PHP is a server-side scripting language that is embedded in HTML. It
is used to manage dynamic content, databases, session tracking,
even build entire e-commerce sites.
3. PHP is integrated with a number of popular databases including
MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL
Server.
4. PHP is pleasingly zippy in its execution, especially when compiled as
an Apache module on the Unix side. The MySQL server, once
started, executes even very complex queries with huge result sets
in record-setting time.
5. PHP supports a number of protocols such as POP3, IMAP, and LDAP.
PHP supports distributed object architectures (COM and CORBA),
which makes n-tier development possible.
6. PHP is forgiving: PHP language tries to be as forgiving as possible.
7. PHP has a familiar C-like syntax.

There are five important characteristics of PHP that make its practical
nature possible: Simplicity, Efficiency, Security, Flexibility, and Familiarity.

EG:
<?php
// PHP code goes here
?>

PHP Features
Here are some more important features of PHP −

1. PHP performs system functions. It can create, open, read, write, and
close the files.
2. PHP can handle forms. It can gather data from files, save data to a
file, through email you can send data, return data to the user.
3. You add, delete, modify elements within your database through
PHP.
4. Access cookies variables and set cookies.
5. Using PHP, you can restrict users to access some pages of your
website.
6. It can encrypt data.

PHP - Syntax
The syntax rules of PHP are very similar to C Language. A PHP code is
stored as a text file with ".php" extension. A '.php' file is essentially a web
page with one or more blocks of PHP code interspersed in the HTML
script.However, it should be opened in a browser with a HTTP protocol
URL.

PHP Tags
PHP defines two methods of using tags for escaping the PHP code from
HTML. See below −

Canonical PHP tags

Canonical PHP Tags


Canonical PHP tags are commonly used to include PHP code within an
HTML file. These tags start with '<?php' and end with '?>'. This is the
finest and widely used method of creating PHP code because it works on
all servers and requires no further configuration. The most universally
effective PHP tag style is −

<?php
echo "Hello World!";
?>

Basic Syntax of PHP


The basic syntax of PHP is very similar to that of C and C++.

Statements in PHP
A statement in PHP is any expression that is followed by a
semicolon (;). Any sequence of valid PHP statements that is
enclosed by the PHP tags is a valid PHP program.

Here is a typical statement in PHP, which in this case assigns a


string of characters to a variable called "$greeting" −

$greeting = "Welcome to PHP!";

A physical line in the text editor doesn't have any significance in


a PHP code. There may be multiple semicolon-terminated
statements in a single line. On the other hand, a PHP statement
may spill over more than one line if required.

Expressions in PHP
An expression is a combination of values, variables, and
operators that produces a result. Tokens are the most basic
building blocks of PHP. For example −

Numbers (3.14159)
Strings ("Hello")
Variables ($name)
Constants (TRUE, FALSE)
Keywords (if, else, while, for, etc.)

<!DOCTYPE html>
<html> O/P:
<body> My first PHP page
Hello World!
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

PHP statements end with a semicolon (;)

PHP Case Sensitivity


In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are not case-sensitive.
<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>"; O/P: Hello World! (3x)
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

all variable names are case-sensitive!

1. <!DOCTYPE html>
2. <html>
3. <body>
4.
5. <?php
6. $color = "red";
7. echo "My car is " . $color . "<br>";
8. echo "My house is " . $COLOR . "<br>";
9. echo "My boat is " . $coLOR . "<br>";
10. ?>
11.
12. </body>
13. </html>

My car is red
My house is
My boat is

PHP Comments
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */
?>

</body>
</html>
PHP - Variables
Variables in PHP are used to store data that can be accessed and modified
across the program. A variable can store a wide range of values, like
numbers, text, arrays and even objects. One of PHP's unique features is
that it is a loosely typed language, which means you are not required to
declare the data type of a variable when you create it. PHP defines the
variable's type based on the value assigned to it.

This freedom makes PHP easier to use, particularly for beginners, because
it allows you to store and manage a variety of data types without having
to design them yourself.

How to Declare a Variable in PHP?


To declare a variable in PHP, just assign a value by typing the $ symbol
followed by the variable name. PHP variables are case-sensitive and
should begin with a letter or an underscore, followed by any number of
letters, numbers or underscores.

Syntax
$variable_name = value;

Example
Here is an example showing how to declare variables in PHP −

// A string value
$name = "John";

// A number (integer)
$age = 25;

// A decimal number (float)


$price = 12.50;

PHP Variable Rules


Here is the list of rules to define a variable in PHP −

1. A variable must start with a $ symbol, then its name.


2. The variable name must start with a letter or underscore (_).
3. A variable name cannot start with a number.
4. The variable name can contain letters, digits or underscores.
5. PHP is case sensitive, so $Name and $name are distinct variables.

Example
See the below example showing how both the variables $Name and
$name are different to each other and see the output of the code.

$Name = "Amit";
$name = "Samay";
echo $Name;
echo $name;
Output
Amit
Samay
Variable Types in PHP
In PHP, the primary variable types are string, integer, float (also known as
double), Boolean, array, object, null, and resource. Below is the example
of each type of variable.

1. String : A sequence of characters.


2. Integer : A whole number (without decimals).
3. Float (Double) : A decimal number.
4. Boolean : Represents true or false values.
5. Array : Stores multiple values in one variable.
6. NULL : Represents a variable with no value.

Automatic Type Conversion of Variables


PHP does a good job of automatically converting types from one to
another when necessary. In the following code, PHP converts a string
variable "y" to "int" to perform addition with another integer variable and
print 30 as the result.

<?php
$x = 10;
$y = "20";

echo "x + y is: ", $x+$y;


?>
x + y is: 30

Output Variables
The PHP echo statement is often used to output data to the screen.

EG 1:

<!DOCTYPE html>
<html>
<body>

<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>

</body>
</html> O/P: I love W3Schools.com!

EG 2:
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

</body>
</html> O/P: 9
PHP is a Loosely Typed Language justify
PHP automatically associates a data type to the variable, depending on its
value. Since the data types are not set in a strict sense, you can do things
like adding a string to an integer without causing an error.

Variables are Assigned by Value


In PHP, variables are always assigned by value. If an expression is
assigned to a variable, the value of the original expression is copied into
it. If the value of any of the variables in the expression changes after the
assignment, it doesnt have any effect on the assigned value.

<?php
$x = 10;
$y = 20;
$z = $x+$y;
echo "(before) z = ". $z . "\n";

$y=5;
echo "(after) z = ". $z . "";
?>
Output:
(before) z = 30
(after) z = 30

Assigning Values to PHP Variables by Reference


You can also use the way to assign values to PHP variables by reference.
In this case, the new variable simply references or becomes an alias for or
points to the original variable. Changes to the new variable affect the
original and vice versa.

To assign by reference, simply prepend an ampersand (&) to the


beginning of the variable which is being assigned (the source variable).

<?php
$x = 10;
$y = &$x;
$z = $x+$y;
echo "x=". $x . " y=" . $y . " z = ". $z . "\n";

$y=20;
$z = $x+$y;
echo "x=". $x . " y=" . $y . " z = ". $z . "";
?>
O/P:
x=10 y=10 z = 20
x=20 y=20 z = 40

Variable Scope
Scope can be defined as the range of availability a variable has to
the program in which it is declared. PHP variables can be one of
four scope types −
1. Local Variables
2. Global Variables
3. Static Variables
4. Function Parameters

Get the Type:

To get the data type of a variable, use the var_dump() function.

O/P:
<!DOCTYPE html> int(5)
<html> string(4) "John"
<body> float(3.14)
<pre> bool(true)
array(3) {
<?php [0]=>
var_dump(5); int(2)
var_dump("John"); [1]=>
var_dump(3.14); int(3)
var_dump(true); [2]=>
var_dump([2, 3, 56]); int(56)
var_dump(NULL); }
?> NULL

</pre>
</body>
</html>

PHP Variables Scope


The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:

● local
● global
● static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:

EX:01
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>
</body></html> O/P: Variable x inside function is
Variable x outside function is: 5

<!DOCTYPE html>
<html>
<body>

EX:02
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

</body></html>
O/P: Variable x inside function is: 5
Variable x outside function is:

PHP The global Keyword

The global keyword is used to access a global variable from within a


function.

To do this, use the global keyword before the variables (inside thefunction):

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest(); // run function


echo $y; // output the new value for variable $y
?>

</body>
</html> O/P: 15

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are


deleted. However, sometimes we want a local variable NOT to be deleted. We
need it for a further job.

To do this, use the static keyword when you first declare the variable:

<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
O/P: 0 1 2
</body></html>
PHP echo and print Statements
echo and print are more or less the same. They are both used to output
data to the screen.

The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple
parameters (although such usage is rare) while print can take one
argument. echo is marginally faster than print.

<!DOCTYPE html>
<html>
<body>

<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple
parameters.";
?>

</body>
</html>
PHP Variable Handling var_dump() Function
The PHP Variable Handling var_dump() function is used to display structured information
such as type and the value of one or more expressions given as arguments to this function.

This function returns all the public, private and protected properties of the objects in the
output. The dump information about arrays and objects is properly indented to show the
recursive structure.

For the built-in integer, float and Boolean variables, the var_dump() function shows the type
and value of the argument variable.

If an object has a special __debugInfo() function, var_dump() follows it. You can also use
var_dump() on many variables simultaneously. This function prints the output immediately,
but it can also be saved using the output-control functions.

Syntax
Below is the syntax of the PHP Variable Handling var_dump() function −

void var_dump ( mixed $value, mixed ...$values )

Parameters
Below are the parameters of the var_dump() function
$value − It is the variable you want to check.
$values − It is the more variables that you want to check. It is an
optional parameter.

Return Value
The var_dump() function does not return anything. It just prints
information on the screen.

What is a $ Variable?
A $ variable is a normal PHP variable that contains a value. A variable can
be allocated a wide range of values, including numbers, texts and arrays.

Normal vs Dynamic Variables


Normal Variable: The declaration of a normal variable is like this −
<?php
$a = 'good';
?>
Dynamic Variable: A dynamic variable takes the value of a normal
variable and treats that as the name of the variable. In the above
example, "good" can be used as the name of a variable by using two
dollar signs "$$" −

<?php
$$a = 'morning';
?>

What is a $$ Variable?
A $$ variable is a variable within a variable. It means that the variable's
name is saved in another variable.

PHP - Constants
A constant in PHP is a name or an identifier for a simple value. A constant
value cannot change during the execution of the PHP script. It basically
improves code readability and maintainability. Constants make it easier to
manage the configuration settings.

They make code easier to read and prevent key values from changing.
Constants can be used anywhere in the application. PHP also contains
built-in constants such as PHP_VERSION. Constants help make the code
simple and secure.

Rules of Constants in PHP


1. By default, a PHP constant is case-sensitive.
2. By convention, constant identifiers are always uppercase.
3. A constant name starts with a letter or underscore, followed by any
number of letters, numbers, or underscore.
4. There is no need to write a dollar sign ($) before a constant,
however one has to use a dollar sign before a variable.

Create a PHP Constant

To create a constant, use the define() function.

Syntax
define(name, value);
Parameters:

● name: Specifies the name of the constant


● value: Specifies the value of the constant

PHP const Keyword

You can also create a constant by using the const keyword.


<!DOCTYPE html>
<html>
<body>

<?php
const MYCAR = "Volvo";

echo MYCAR;
?>

</body>
</html> O/P: Volvo

const vs. define()

● const cannot be created inside another block scope, like inside


a function or inside an if statement.
● define can be created inside another block scope.

You can also use an array as the value of a constant. Take a look
at the following example −
<?php
define(
$name="LANGS",
$value=array('PHP', 'Java', 'Python')
);
var_dump(LANGS);
?>

It will produce the following output −

array(3) {
[0]=>
string(3) "PHP"
[1]=>
string(4) "Java"
[2]=>
string(6) "Python"
}

Using the constant() Function


The echo statement outputs the value of the defined constant.
You can also use the constant() function. It returns the value of
the constant indicated by name.

constant(string $name): mixed


The constant() function is useful if you need to retrieve the value
of a constant, but do not know its name. I.e. it is stored in a
variable or returned by a function.
<?php
define("MINSIZE", 50);

echo MINSIZE;
echo PHP_EOL;
// same thing as the previous line
echo constant("MINSIZE");
?>
O/P:
50
50

PHP Magic Constants

The magical constants in PHP are predefined constants. They are available
to any script on which they run, and they change depending on where
they are used. All these "magical" constants are resolved at compile time,
unlike regular constants, which are resolved at runtime.

There are nine magical constants in PHP. These special constants are case
insensitive. The list of Magic Constants are as follows −

Constant Description

__CLASS__ If used inside a class, the class name is returned.

__DIR__ The directory of the file.

__FILE__ The file name including the full path.

__FUNCTION_ If inside a function, the function name is returned.

__LINE__ The current line number.


__METHOD__ If used inside a function that belongs to a class, both
class and function name is returned.

_NAMESPACE_ If used inside a namespace, the name of the


namespace is returned.

__TRAIT__ If used inside a trait, the trait name is returned.

ClassName::cl Returns the name of the specified class and the


ass name of the namespace, if any.

Line:
<?php
$x="Hello World";
echo "$x. The current Line number is " . __LINE__ . ".";
?>
O/P: Hello World. The current Line number is 5.
FILE:
<?php
$x="Hello World";
echo "$x. Current PHP script name is " . __FILE__ . ".";
?>
O/P:Hello World. Current PHP script name is C:\xampp\htdocs\
hello.php.
DIR:
<?php
$x="Hello World";
echo "$x. Directory of the Current PHP script name is " .
__DIR__ . ".";
?>
O/P: Hello World. Directory of the Current PHP script name is C:\
xampp\htdocs.
FUNCTION:
<?php
function hello(){
$x="Hello World";
echo "$x. The function name is ". __FUNCTION__ . "";
}
hello();
?>
O/P: Hello World. The function name is hello
CLASS:
<?php
class myclass {
public function __construct() {
echo "Inside the constructor of ". __CLASS__ .
PHP_EOL;
}
function getClassName(){
echo "from an instance method of " . __CLASS__ . "";
}
}
$obj = new myclass;
$obj->getClassName();
?>
O/P: Inside the constructor of myclass
from an instance method of myclass

METHOD:
<?php
class myclass {
public function __construct() {
echo "Calling " . __METHOD__ . " of " .
__CLASS__ ."<br>";
}
function mymethod(){
echo "Calling " . __METHOD__ . " of " .
__CLASS__ ."";
}
}
$obj = new myclass;
$obj->mymethod();
?>
O/P: Calling myclass::__construct of myclass
Calling myclass::mymethod of myclass

TRAIT:
<?php
trait mytrait {
public function hello() {
echo "Hello World from " . __TRAIT__ ."";
}
}
class myclass {
use mytrait;
}
$obj = new myclass();
$obj->hello();
?>
O/P: Hello World from mytrait

NAMESPACE:
<?php
namespace myspace;
class myclass {
public function __construct() {
echo "Name of the class: " . __CLASS__ . " in " .
__NAMESPACE__ . "";
}
}
$class_name = __NAMESPACE__ . '\myclass';
$a = new $class_name;
?>
O/P: Name of the class: myspace\myclass in myspace

CLASSNAME::CLASS
<?php
namespace myspace;
class myclass {
public function __construct() {
echo "Name of the class: " . myclass::class ;
}
}
use myspace;
$a = new myclass;
?>
O/P: Name of the class: myspace\myclass

PHP Operators
Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Increment/Decrement operators
● Logical operators
● String operators
● Array operators
● Conditional assignment operators

Arithmetic Operators in PHP


We use Arithmetic operators to perform mathematical operations like addition,
subtraction, multiplication, division, etc. on the given operands. Arithmetic
operators (excluding the increment and decrement operators) always work on
two operands, however the type of these operands should be the same.

The following table highlights the arithmetic operators that are supported by
PHP. Assume variable "$a" holds 42 and variable "$b" holds 20 −

Operator Description Example

+ Adds two operands $a + $b = 62

- Subtracts second operand from the first $a - $b = 22

* Multiply both operands $a * $b = 840

/ Divide numerator by de-numerator $a / $b = 2.1

% Modulus Operator and remainder of after an $a % $b = 2


integer division

++ Increment operator, increases integer value $a ++ = 43


by one

-- Decrement operator, decreases integer value $a -- = 42


by one

PHP CODE:
<?php
// 1. Basic Arithmetic Operators
$a = 12;
$b = 4;
echo "1. Basic Arithmetic Operators:\n";
echo "a + b = " . ($a + $b) . "\n";
echo "a - b = " . ($a - $b) . "\n";
echo "a * b = " . ($a * $b) . "\n";
echo "a / b = " . ($a / $b) . "\n";
echo "a % b = " . ($a % $b) . "\n\n";

// 2. Arithmetic with Negative Numbers


$x = -5;
$y = 3;
echo "2. With Negative Numbers:\n";
echo "x + y = " . ($x + $y) . "\n";
echo "x * y = " . ($x * $y) . "\n\n";

// 3. Floating-Point Arithmetic
$f1 = 7.5;
$f2 = 2.0;
echo "3. Floating-Point Numbers:\n";
echo "f1 / f2 = " . ($f1 / $f2) . "\n";
echo "f1 * f2 = " . ($f1 * $f2) . "\n\n";

// 4. Increment and Decrement


$num = 5;
echo "4. Increment and Decrement:\n";
echo "Initial: $num\n";
echo "Post-increment: " . $num++ . " (Now: $num)\n";
echo "Pre-increment: " . ++$num . "\n";
echo "Post-decrement: " . $num-- . " (Now: $num)\n";
echo "Pre-decrement: " . --$num . "\n";
?>

OUTPUT:
1. Basic Arithmetic Operators:
a + b = 16
a-b=8
a * b = 48
a/b=3
a%b=0

2. With Negative Numbers:


x + y = -2
x * y = -15

3. Floating-Point Numbers:
f1 / f2 = 3.75
f1 * f2 = 15

4. Increment and Decrement:


Initial: 5
Post-increment: 5 (Now: 6)
Pre-increment: 7
Post-decrement: 7 (Now: 6)
Pre-decrement: 5

Comparison Operators in PHP


You would use Comparison operators to compare two operands and find the
relationship between them. They return a Boolean value (either true or false)
based on the outcome of the comparison.

The following table highlights the comparison operators that are supported by
PHP. Assume variable $a holds 10 and variable $b holds 20, then −

Operato Description Example


r

== Checks if the value of two operands are equal or not, ($a == $b)
if yes then condition becomes true. is not true

!= Checks if the value of two operands are equal or not, ($a != $b) is
if values are not equal then condition becomes true. true

> Checks if the value of left operand is greater than the ($a > $b) is
value of right operand, if yes then condition becomes false
true.

< Checks if the value of left operand is less than the ($a < $b) is
value of right operand, if yes then condition becomes true
true.

>= Checks if the value of left operand is greater than or ($a >= $b)
equal to the value of right operand, if yes then is false
condition becomes true.

<= Checks if the value of left operand is less than or ($a <= $b)
equal to the value of right operand, if yes then is true
condition becomes true.

PHP CODE:
<?php
echo "PHP COMPARISON OPERATORS DEMO\n\n";

// 1. EQUAL (==)
$a = 5;
$b = "5"; // same value, different type
echo "1. Equal (==):\n";
var_dump($a == $b); // true
echo "\n";

// 2. IDENTICAL (===)
echo "2. Identical (===):\n";
var_dump($a === $b); // false because types differ
echo "\n";

// 3. NOT EQUAL (!= or <>)


$c = 10;
$d = 20;
echo "3. Not Equal (!=):\n";
var_dump($c != $d); // true
echo " Also works with (<>): ";
var_dump($c <> $d); // true
echo "\n";

// 4. GREATER THAN (>)


echo "4. Greater Than (>):\n";
var_dump($d > $c); // true
echo "\n";

// 5. LESS THAN (<)


echo "5. Less Than (<):\n";
var_dump($c < $d); // true
echo "\n";

// 6. GREATER THAN OR EQUAL TO (>=)


echo "6. Greater Than or Equal To (>=):\n";
var_dump($c >= 10); // true
echo "\n";

// 7. LESS THAN OR EQUAL TO (<=)


echo "7. Less Than or Equal To (<=):\n";
var_dump($c <= 9); // false
echo "\n";

// 8. SPACESHIP OPERATOR (<=>)


// Returns: -1 (left < right), 0 (equal), 1 (left > right)
echo "8. Spaceship Operator (<=>):\n";
echo "Compare 10 <=> 20 = " . (10 <=> 20) . "\n"; // -1
echo "Compare 20 <=> 20 = " . (20 <=> 20) . "\n"; // 0
echo "Compare 30 <=> 20 = " . (30 <=> 20) . "\n"; // 1
?>
OUTPUT:
PHP COMPARISON OPERATORS DEMO
1. Equal (==):
bool(true)

2. Identical (===):
bool(false)

3. Not Equal (!=):


bool(true)
Also works with (<>): bool(true)

4. Greater Than (>):


bool(true)

5. Less Than (<):


bool(true)

6. Greater Than or Equal To (>=):


bool(true)
7. Less Than or Equal To (<=):
bool(false)

8. Spaceship Operator (<=>):


Compare 10 <=> 20 = -1
Compare 20 <=> 20 = 0
Compare 30 <=> 20 = 1

Logical Operators in PHP


You can use Logical operators in PHP to perform logical operations on multiple
expressions together. Logical operators always return Boolean values, either true
or false.

Logical operators are commonly used with conditional statements and loops to
return decisions according to the Boolean conditions. You can also combine them
to manipulate Boolean values while dealing with complex expressions.

The following table highlights the logical operators that are supported by PHP.

Assume variable $a holds 10 and variable $b holds 20, then −

Operator Description Example

and Called Logical AND operator. If both the (A and B) is true


operands are true then condition becomes
true.

or Called Logical OR Operator. If any of the (A or B) is true


two operands are non zero then condition
becomes true.

&& Called Logical AND operator. If both the (A && B) is true


operands are non zero then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true


two operands are non zero then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is false


reverses the logical state of its operand. If
a condition is true then Logical NOT
operator will make false.

PHP CODE:
<?php
echo "PHP LOGICAL OPERATORS DEMO\n\n";

// 1. AND (&& or and)


$a = true;
$b = false;
echo "1. Logical AND (&&):\n";
// Both must be true to return true
var_dump($a && $b); // false
echo " Same with 'and': ";
var_dump($a and $b); // false
echo "\n";

// 2. OR (|| or or)
$c = true;
$d = false;
echo "2. Logical OR (||):\n";
// At least one true returns true
var_dump($c || $d); // true
echo " Same with 'or': ";
var_dump($c or $d); // true
echo "\n";

// 3. NOT (!)
$e = false;
echo "3. Logical NOT (!):\n";
// Reverses the value
var_dump(!$e); // true
?>
OUTPUT:
PHP LOGICAL OPERATORS DEMO

1. Logical AND (&&):


bool(false)
Same with 'and': bool(false)

2. Logical OR (||):
bool(true)
Same with 'or': bool(true)

3. Logical NOT (!):


bool(true)

Assignment Operators in PHP


You can use Assignment operators in PHP to assign or update the values of a
given variable with a new value. The right-hand side of the assignment operator
holds the value and the left-hand side of the assignment operator is the variable
to which the value will be assigned.

The data type of both the sides should be the same, else you will get an error.
The associativity of assignment operators is from right to left. PHP supports two
types of assignment operators −

Simple Assignment Operator − It is the most commonly used operator. It is


used to assign value to a variable or constant.
Compound Assignment Operators − A combination of the assignment
operator (=) with other operators like +, *, /, etc.
The following table highlights the assignment operators that are supported by
PHP −

Operato Description Example


r

= Simple assignment operator, Assigns values C = A + B will


from right side operands to left side operand assign value of A +
B into C

+= Add AND assignment operator, It adds right C += A is


operand to the left operand and assign the equivalent to C = C
result to left operand +A

-= Subtract AND assignment operator, It C -= A is


subtracts right operand from the left operand equivalent to C = C
and assign the result to left operand -A

*= Multiply AND assignment operator, It C *= A is


multiplies right operand with the left operand equivalent to C = C
and assign the result to left operand *A

/= Divide AND assignment operator, It divides left C /= A is


operand with the right operand and assign the equivalent to C = C
result to left operand /A

%= Modulus AND assignment operator, It takes C %= A is


modulus using two operands and assign the equivalent to C = C
result to left operand %A

PHP CODE:
<?php
echo "PHP ASSIGNMENT OPERATORS DEMO\n\n";

// 1. Simple Assignment (=)


$a = 10;
echo "1. Simple Assignment (=): a = 10\n";
echo "a = $a\n\n";

// 2. Addition Assignment (+=)


$a += 5; // same as a = a + 5
echo "2. Addition Assignment (+=): a += 5 → a = a + 5\n";
echo "a = $a\n\n"; // 15

// 3. Subtraction Assignment (-=)


$a -= 3; // same as a = a - 3
echo "3. Subtraction Assignment (-=): a -= 3 → a = a - 3\n";
echo "a = $a\n\n"; // 12

// 4. Multiplication Assignment (*=)


$a *= 2; // same as a = a * 2
echo "4. Multiplication Assignment (*=): a *= 2 → a = a * 2\n";
echo "a = $a\n\n"; // 24

// 5. Division Assignment (/=)


$a /= 4; // same as a = a / 4
echo "5. Division Assignment (/=): a /= 4 → a = a / 4\n";
echo "a = $a\n\n"; // 6

// 6. Modulus Assignment (%=)


$a %= 5; // same as a = a % 5
echo "6. Modulus Assignment (%=): a %= 5 → a = a % 5\n";
echo "a = $a\n\n"; // 1
?>

OUTPUT:

PHP ASSIGNMENT OPERATORS DEMO


1. Simple Assignment (=): a = 10
a = 10
2. Addition Assignment (+=): a += 5 → a = a + 5
a = 15
3. Subtraction Assignment (-=): a -= 3 → a = a - 3
a = 12
4. Multiplication Assignment (*=): a *= 2 → a = a * 2
a = 24
5. Division Assignment (/=): a /= 4 → a = a / 4
a=6
6. Modulus Assignment (%=): a %= 5 → a = a % 5
a=1

String Operators in PHP


There are two operators in PHP for working with string data types −

The "." (dot) operator is PHP's concatenation operator. It joins two


string operands (characters of right hand string appended to left
hand string) and returns a new string.
PHP also has the ".=" operator which can be termed as the
concatenation assignment operator. It updates the string on its left
by appending the characters of right hand operand.

<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2; //Hello world!
?>

Array Operators in PHP


PHP defines the following set of symbols to be used as operators on array
data types −

Symb Example Name Result


ol
+ $a + $b Union Union of $a and $b.

== $a == $b Equality TRUE if $a and $b have the same


key/value pairs.

=== $a === $b Identity TRUE if $a and $b have the same


key/value pairs in the same order and
of the same types.

!= $a != $b Inequali TRUE if $a is not equal to $b.


ty

<> $a <> $b Inequali TRUE if $a is not equal to $b.


ty

!== $a !== $b Non TRUE if $a is not identical to $b.


identity

PHP CODE:
<?php
echo "PHP ARRAY OPERATORS DEMO (Simple Version)\n\n";

// Define simple arrays


$first = ["x" => 1, "y" => 2];
$second = ["y" => 3, "z" => 4];
$third = ["x" => 1, "y" => 2];
$fourth = ["y" => 2, "x" => 1]; // Same values, different order
$fifth = ["x" => 1, "y" => "2"]; // Same values, different type

// 1. Union (+)
echo "1. Union (+): \$first + \$second\n";
$result = $first + $second; // Keeps keys from $first
print_r($result);
echo "\n";

// 2. Equality (==)
echo "2. Equality (==): \$first == \$third\n";
var_dump($first == $third); // true
echo " \$first == \$fourth (same content, diff order)\n";
var_dump($first == $fourth); // true
echo " \$first == \$fifth (value same, type diff)\n";
var_dump($first == $fifth); // true
echo "\n";

// 3. Identity (===)
echo "3. Identity (===): \$first === \$third\n";
var_dump($first === $third); // true
echo " \$first === \$fourth (different order)\n";
var_dump($first === $fourth); // false
echo " \$first === \$fifth (type mismatch)\n";
var_dump($first === $fifth); // false
echo "\n";

// 4. Not Equal (!= and <>)


echo "4. Not Equal (!= and <>): \$first != \$second\n";
var_dump($first != $second); // true
echo " \$first <> \$second\n";
var_dump($first <> $second); // true
echo "\n";

// 5. Not Identical (!==)


echo "5. Not Identical (!==): \$first !== \$fifth\n";
var_dump($first !== $fifth); // true
echo " \$first !== \$third\n";
var_dump($first !== $third); // false
?>
OUTPUT:
PHP ARRAY OPERATORS DEMO (Simple Version)

1. Union (+): $first + $second


Array
(
[x] => 1
[y] => 2
[z] => 4
)

2. Equality (==): $first == $third


bool(true)
$first == $fourth (same content, diff order)
bool(true)
$first == $fifth (value same, type diff)
bool(true)

3. Identity (===): $first === $third


bool(true)
$first === $fourth (different order)
bool(false)
$first === $fifth (type mismatch)
bool(false)

4. Not Equal (!= and <>): $first != $second


bool(true)
$first <> $second
bool(true)

5. Not Identical (!==): $first !== $fifth


bool(true)
$first !== $third
bool(false)

Conditional Operators in PHP


There is one more operator in PHP which is called conditional operator. It
is also known as ternary operator. It first evaluates an expression for a
true or false value and then executes one of the two given statements
depending upon the result of the evaluation.

Opera Description Example


tor

?: Conditional Expression If Condition is true ? Then value X :


Otherwise value Y

<?php
// if empty($user) = TRUE, set $status = "anonymous"
echo $status = (empty($user)) ? "anonymous" : "logged in";
echo("<br>");

$user = "John Doe";


// if empty($user) = FALSE, set $status = "logged in"
echo $status = (empty($user)) ? "anonymous" : "logged in";
?>
//anonymous
logged in

PHP STRINGS:
A string is a sequence of characters, like 'PHP supports string operations.' A
string in PHP as an array of bytes and an integer indicating the length of the
buffer. In PHP, a character is the same as a byte. This means that PHP only
supports a 256-character set, and hence does not offer native Unicode
support.PHP supports single quoted as well as double quoted string formation.

PHP CODE:

<?php
echo "PHP STRING OPERATORS\n\n";

// 1. Concatenation
$f = "John";
$l = "Doe";
$full = $f . " " . $l;
echo "1. Concatenation: \$f . \$l\n";
echo "Full Name: $full\n\n";

// 2. String Length
$s = "Hello";
echo "2. String Length: strlen(\$s)\n";
echo "Length: " . strlen($s) . "\n\n";
// 3. Find Position of Substring
$t = "PHP is fun";
echo "3. Find Position: strpos(\$t, 'is')\n";
echo "Position: " . strpos($t, 'is') . "\n\n";

// 4. Case Conversion
$u = "hello";
echo "4. Case Conversion:\n";
echo "Upper: " . strtoupper($u) . "\n";
echo "Lower: " . strtolower($u) . "\n";
echo "First Letter Capital: " . ucwords($u) . "\n\n";

// 5. Substring Extraction
$v = "Programming with PHP";
echo "5. Substring: substr(\$v, 0, 11)\n";
echo "Substring: " . substr($v, 0, 11) . "\n\n";

// 6. String Replace
$o = "PHP is cool";
$new = str_replace("cool", "awesome", $o);
echo "6. Replace: str_replace('cool', 'awesome', \$o)\n";
echo "New Text: $new\n\n";

// 7. String Compare
$a = "apple";
$b = "banana";
echo "7. Compare: strcmp(\$a, \$b)\n";
echo "Comparison: " . strcmp($a, $b) . "\n"; // -1 if $a < $b, 0 if equal
?>

OUTPUT:

PHP STRING OPERATORS

1. Concatenation: $f . $l
Full Name: John Doe

2. String Length: strlen($s)


Length: 5

3. Find Position: strpos($t, 'is')


Position: 4

4. Case Conversion:
Upper: HELLO
Lower: hello
First Letter Capital: Hello

5. Substring: substr($v, 0, 11)


Substring: Programming

6. Replace: str_replace('cool', 'awesome', $o)


New Text: PHP is awesome

7. Compare: strcmp($a, $b)


Comparison: -1

Additional PHP String Functions


1. Trimming

○ trim() – Removes whitespace or other characters from the


beginning and end of a string.

○ ltrim() – Removes whitespace or other characters from the left


side.

○ rtrim() – Removes whitespace or other characters from the right


side.
○ php
$str = " Hello PHP ";
○ echo trim($str); // "Hello PHP"
2. String to Array

○ explode() – Splits a string into an array based on a delimiter.

○ implode() – Joins array elements into a single string using a


delimiter.
php
$str = "apple,banana,orange";
○ $arr = explode(",", $str); // ["apple", "banana",
"orange"]
3. String Replacement with Callback

○ preg_replace() – Perform regular expression search and replace.


php
$str = "Hello 123";
○ echo preg_replace("/\d+/", "World", $str); // "Hello
World"
4. Searching for a Substring

○ strpos() – Finds the position of the first occurrence of a substring.

○ strrpos() – Finds the position of the last occurrence.

○ substr_count() – Counts how many times a substring occurs.


php
$str = "PHP is cool, PHP is great!";echo
substr_count($str, "PHP"); // 2
5. Formatting Strings

○ sprintf() – Returns a formatted string.


○ printf() – Prints a formatted string directly.
php
echo sprintf("Hello, %s!", "John"); // Hello, John!
6. String Encoding and Decoding

○ htmlspecialchars() – Converts special characters to HTML


entities.

○ html_entity_decode() – Converts HTML entities to their respective


characters.
PHP:
$str = "<div>Hello</div>";
○ echo htmlspecialchars($str); //
&lt;div&gt;Hello&lt;/div&gt;
7. Substrings & Character Access

○ substr() – Extract a part of the string.

○ substr_replace() – Replace part of the string with another string.


php
$str = "Hello World";
○ echo substr_replace($str, "PHP", 6, 5); // Hello PHP
8. String Conversion between Encodings

○ mb_convert_encoding() – Converts the encoding of a string.


echo mb_convert_encoding($str, "UTF-8", "ISO-8859-1");
○ PHP:
○ <?php
○ // Original string with ISO-8859-1 encoding
○ $str = "Héllo";
○ // Convert from ISO-8859-1 to UTF-8 encoding
○ $converted_str = mb_convert_encoding($str, "UTF-8", "ISO-
8859-1");
○ // Output the original and converted string
○ echo "Original String: " . $str . "\n";
○ echo "Converted String: " . $converted_str . "\n";?>

O/P: Original String: Héllo


Converted String: Héllo

9. String Reversal
strrev() – Reverses a string.
php
$str = "hello";

echo strrev($str); // "olleh"

9. Character Counting
charAt() – Returns a character from the string at the specified position.
str_repeat() – Repeat a string for a given number of times.
php
echo str_repeat("Hello ", 3); // Hello Hello Hello

FLOW CONTROL STATEMENTS

1. Decision-making is the anticipation of conditions occurring during


the execution of a program and specified actions taken according to
the conditions.
2. You can use conditional statements in your code to make your
decisions. The ability to implement conditional logic is one of the
fundamental requirements of a programming language.
3. A computer program by default follows a simple input-process-
output path sequentially.

In PHP we have the following conditional statements:

● if statement - executes some code if one condition is true


● if...else statement - executes some code if a condition is true and
another code if that condition is false
● if...elseif...else statement - executes different codes for more
than two conditions
● switch statement - selects one of many blocks of code to be
executed
● Nested if Statement-You can use an if statement within another if
statement to verify multiple conditions in a logical way

Syntax:
if (expr)
statement1
else
statement2

IF:
<?php
$t = 14;
if ($t < 20) {
echo "Have a good day!";
}
?> // Have a good day!

if...else Statement
if (condition) {
// code to be executed if condition is true;
} else {
// code to be executed if condition is false;
}

CODE:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?> //Have a good day!

The if...elseif...else Statement


The if...elseif...else statement executes different codes for more
than two conditions.
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;

<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
O/P: The hour (of the server) is 10, and will give the following message:
Have a good day!
PHP - Switch Statement

The switch statement allows many if-else conditions for a single variable.
Sometimes you need to compare a variable to multiple values and run separate
code for each one. used to perform different actions based on different
conditions.reduce code complexity and improve readability.

Syntax:
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block

CODE:

<?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!";
}
?> //Your favorite color is red!
Using switch-endswitch Statement
PHP allows the usage of alternative syntax by delimiting the switch
construct with switch-endswitch statements.

CODE:

<?php
$x=0;
switch ($x) :
case 0:
echo "x equals 0";
break;
case 1:
echo "x equals 1 \n";
break;
case 2:
echo "x equals 2 \n";
break;
default:
echo "None of the above";
endswitch
?> //x equals 0

Using switch to Display the Current Day


Obviously, you needn't write a break to terminate the default case, it
being the last case in the switch construct.

<?php
$d = date("D");

switch ($d){
case "Mon":
echo "Today is Monday";
break;

case "Tue":
echo "Today is Tuesday";
break;

case "Wed":
echo "Today is Wednesday";
break;

case "Thu":
echo "Today is Thursday";
break;

case "Fri":
echo "Today is Friday";
break;

case "Sat":
echo "Today is Saturday";
break;

case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?> //Today is Monday

LOOPING STATEMENTS:
For Loop: Loops through a block of code a specified number of times.
Foreach Loop: Loops through a block of code for each element in an array.
While Loop: Loops through a block of code if and as long as a specified
condition is true.
Do-while Loop: Loops through a block of code once, and then repeats the
loop as long as a special condition is true.
Break statement: It is used to terminate the execution of a loop
prematurely.
Continue Statement: It is used to halt the current iteration of a loop.

1. PHP For Loop


The for loop is used when the number of iterations is known in advance.

Syntax:
for (initialization; condition; increment) {
// code to be executed;
}

Example:
<?php
$a = 0;
$b = 0;

for( $i = 0; $i < 5; $i++ ) {


$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b = $b");


?>

Output:
At the end of the loop a = 50 and b = 25

2. PHP Foreach Loop


The foreach loop is used to iterate over arrays.

Syntax:
foreach (array as value) {
// code to be executed;
}

Example:
<?php
$array = array(1, 2, 3, 4, 5);
foreach( $array as $value ) {
echo "Value is $value \n";
}
?>

Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

3. PHP While Loop


The while loop executes code as long as the condition evaluates to true.

Syntax:
while (condition) {
// code to be executed;
}

Example:
<?php
$i = 0;
$num = 50;

while($i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num");


?>

Output:
Loop stopped at i = 10 and num = 40

4. PHP Do-while Loop


The do-while loop executes the code block once before checking the condition.

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

Example:
<?php
$i = 0;
$num = 0;

do {
$i++;
} while( $i < 10 );
echo ("Loop stopped at i = $i");
?>

Output:
Loop stopped at i = 10

PHP Break Statement


The break keyword terminates the loop when a certain condition is met.

Example:
<?php
$i = 0;

while( $i < 10) {


$i++;
if( $i == 3 ) break;
}
echo ("Loop stopped at i = $i");
?>

Output:
Loop stopped at i = 3

PHP Continue Statement


The continue keyword skips the current iteration and continues with the next
one.

Example:
<?php
$array = array(1, 2, 3, 4, 5);

foreach( $array as $value ) {


if( $value == 3 ) continue;
echo "Value is $value \n";
}
?>

Output:
Value is 1
Value is 2
Value is 4
Value is 5
PHP Arrays

Introduction

An array is a data structure that stores one or more data values having
some relation among them, in a single variable. For example, if you want
to store the marks of 10 students in a class, then instead of defining 10
different variables, it's easier to define an array of length 10.

Arrays in PHP behave a little differently than the arrays in C, as PHP is a


dynamically typed language whereas C is statically typed.

How to Define an Array in PHP?

In PHP, there are two ways to define an array:

1. Using the array() function

2. Using square brackets []

Using array() Function

Syntax: array(mixed ...$values): array

Each value may be a singular value or a key-value pair. The key-value


association is denoted by the '=>' symbol.

Example:

<?php
$arr1 = array(10, "asd", 1.55, true);
$arr2 = array("one"=>1, "two"=>2, "three"=>3);
$arr3 = array(
array(10, 20, 30),
array("Ten", "Twenty", "Thirty"),
array("physics"=>70, "chemistry"=>80, "maths"=>90)
);
print_r($arr3);
?>

Output:

Array
(
[0] => Array
(
[0] => 10
[1] => 20
[2] => 30
)
[1] => Array
(
[0] => Ten
[1] => Twenty
[2] => Thirty
)
[2] => Array
(
[physics] => 70
[chemistry] => 80
[maths] => 90
)
)

Using Square Brackets [ ]

Example:

<?php
$arr1 = [10, "asd", 1.55, true];
$arr2 = ["one"=>1, "two"=>2, "three"=>3];
$arr3 = [ [10, 20, 30],
["Ten", "Twenty", "Thirty"],
["physics"=>70, "chemistry"=>80, "maths"=>90] ];
?>

Types of Arrays in PHP

1. Indexed Array

Example:
$fruits = ["Apple", "Banana", "Orange"];

2. Associative Array
Example:
$marks = ["Ankit" => 85, "Eisha" => 90, "Deepak" => 78];

3. Multidimensional Array

Example:
$students = [
["Ankit", 85, "A"],
["Eisha", 90, "A+"],
["Deepak", 78, "B"]
];

Accessing Array Elements

<?php
$arr1 = [10, 20, 30];
$arr2 = array("one"=>1, "two"=>2, "three"=>3);

var_dump($arr1[1]);
var_dump($arr2["two"]);
?>

Output:

int(20)
int(2)

Properties of Arrays in PHP

- Arrays in PHP are ordered maps that associate keys to values.

- Can be used to implement stacks, queues, lists, dictionaries, etc.

- PHP supports both indexed and associative arrays.

- PHP arrays are flexible and can hold any data type.

- Built-in functions like array_push(), array_pop(), and array_merge() are


available.

Indexed and Associative Arrays in PHP


In PHP, the array elements may be a collection of key-value pairs or it may
contain values only.
If the array consists of values only, it is said to be an indexed array, as
each element is identified by an incrementing index, starting with "0".

Creating an Indexed Array


An indexed array in PHP may be created either by using the array()
function or with the square bracket syntax.
$arr1 = array("a", 10, 9.99, true);
$arr2 = ["a", 10, 9.99, true];

Structure of an Indexed Array


Each element in the array has a positional index, the first element being
at index "0".
The var_dump() function reveals the structured information of these
arrays as −

array(4) {
[0]=>
string(1) "a"
[1]=>
int(10)
[2]=>
float(9.99)
[3]=>
bool(true)
}

Traversing an Indexed Array in PHP


Any type of PHP loop can be employed to traverse an array. If we want to
use a for or while loop,
we have to find the number of elements in the array with count() function
and use its value as the test condition.

Example using for loop:


<?php
$numbers = array(10, 20, 30, 40, 50);
for ($i=0; $i<count($numbers); $i++){
echo "numbers[$i] = $numbers[$i]
";
}
?>

Example using while loop in reverse order:


<?php
$numbers = array(10, 20, 30, 40, 50);
$i = count($numbers)-1;
while ($i>=0){
echo "numbers[$i] = $numbers[$i]
";
$i--;
}
?>

Accessing and Modifying Array Elements


You can access any value using array[index] and modify it similarly.
Reversing the elements into a new array:
<?php
$arr1 = array(10, 20, 30, 40, 50);
$size = count($arr1);
for ($i=0; $i<$size; $i++){
$arr2[$size-$i-1] = $arr1[$i];
}
?>

Traversing using foreach:


<?php
$arr1 = [10, 20, 30, 40, 50];
foreach ($arr1 as $val){
echo "$val
";
}
?>

With keys:
<?php
foreach ($arr1 as $key => $val){
echo "arr1[$key] = $val
";
}
?>

Mixed Arrays:
PHP assigns indexes to values without keys:
<?php
$arr1 = [10, 20, "vals" => ["ten", "twenty"], 30, 40, 50];
var_dump($arr1);
?>

Properties of Indexed Arrays:


- Index starts at 0.
- Supports multiple data types.
- Dynamically resizable.
- Easily traversed using loops.

Associative Arrays in PHP:


Use key-value pairs. Keys can be strings or numbers (cast accordingly).

Syntax:
$arr1 = array("key"=>"value", ...);
$arr2 = ["key"=>"value", ...];

Example:
$arr1 = array(
10=>"hello",
5.75=>"world",
-5=>"foo",
false=>"bar"
);

Iterating Associative Arrays:


Using foreach:
<?php
$capitals = array("Maharashtra"=>"Mumbai",
"Telangana"=>"Hyderabad", "UP"=>"Lucknow",
"Tamilnadu"=>"Chennai");
foreach ($capitals as $k=>$v) {
echo "Capital of $k is $v
";
}
?>

Using array_search():
<?php
foreach ($capitals as $pair) {
$cap = array_search($pair, $capitals);
echo "Capital of $cap is $capitals[$cap]
";
}
?>

Using for loop:


<?php
$keys=array_keys($capitals);
for ($i=0; $i<count($keys); $i++){
$cap = $keys[$i];
echo "Capital of $cap is $capitals[$cap]
";
}
?>

Accessing and Modifying Using Keys:


<?php
$arr1 = array("a"=>10, "b"=>20, "c"=>30, "d"=>40);
foreach ($arr1 as $k=>$v){
$arr2[$k] = $v*2;
}
print_r($arr2);
?>

PHP Built-in Functions and User-defined Functions


1. PHP Built-in Functions
PHP comes with a large number of built-in functions that perform many useful
tasks—from string manipulation to date handling, file processing, and more.

2. PHP User-defined Functions


Besides the built-in functions, PHP allows developers to create their own
functions.

● A function is a reusable block of code.

● It only executes when called.

● It starts with the function keyword.

Syntax:

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

3. Creating and Calling a Function

Example:

function myMessage() {
echo "Hello world!";
}
myMessage(); // Function call

● The function myMessage() will output "Hello world!" when called.

● Function names are not case-sensitive.

4. PHP Function Arguments


Functions can accept data using arguments.

Example with one argument:

function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
Example with two arguments:

function familyName($fname, $year) {


echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");

5. Default Argument Values


You can assign default values to arguments.

Example:

function setHeight($minheight = 50) {


echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // Uses default 50

6. Returning Values from Functions


Functions can return values using the return statement.

Example:

function sum($x, $y) {


return $x + $y;
}

echo sum(5, 10); // Outputs: 15

7. Passing Arguments by Reference


By default, PHP passes arguments by value. Use & to pass by reference.

Example:

function add_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num; // Outputs: 7

8. Variable Number of Arguments (Variadic Functions)


Use ... to allow a variable number of parameters.
Example:

function sumMyNumbers(...$x) {
$n = 0;
foreach ($x as $num) {
$n += $num;
}
return $n;
}

echo sumMyNumbers(5, 2, 6, 2, 7, 7); // Outputs: 29

Only the last argument can be variadic.

9. PHP is a Loosely Typed Language


PHP doesn't require you to declare variable types. It converts types
automatically.

Example:

function addNumbers(int $a, int $b) {


return $a + $b;
}

echo addNumbers(5, "5 days"); // Outputs: 10 (no error)

10. Enabling Strict Type Declarations


PHP 7 allows for strict type declarations. If you want PHP to enforce types, use
declare(strict_types=1) at the beginning of the file.

Example (Without strict types):

function addNumbers(int $a, int $b) {


return $a + $b;
}

echo addNumbers(5, "5 days"); // Outputs: 10 (without strict)

Example (With strict types):

<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {


return $a + $b;
}

echo addNumbers(5, "5 days"); // Error: Fatal error: Uncaught TypeError


?>
11. PHP Return Type Declarations
PHP 7 supports Type Declarations for the return statement.

Example:

<?php declare(strict_types=1); // strict requirement

function addNumbers(float $a, float $b) : float {


return $a + $b;
}

echo addNumbers(1.2, 5.2); // Outputs: 6.4

You can specify a different return type from the argument types, but ensure the
return is the correct type:

<?php declare(strict_types=1); // strict requirement

function addNumbers(float $a, float $b) : int {


return (int)($a + $b);
}

echo addNumbers(1.2, 5.2); // Outputs: 6


?>

PHP Call by Value


Call by Value is the default method of passing arguments to functions in PHP. In
this method, when an argument is passed to a function, PHP creates a copy of
the argument and passes it to the function. Any changes made to the argument
inside the function do not affect the original variable outside the function.

Example:
<?php
function addTen($num) {
$num = $num + 10;
echo "Inside function: $num<br>";
}

$value = 5;
addTen($value); // Passing the value of $value
echo "Outside function: $value"; // The value remains unchanged
?>

Output:

Inside function: 15
Outside function: 5
In the above example:

● $value is passed to the addTen() function.

● Inside the function, a copy of $value is modified.

● The original $value outside the function remains unchanged because the
argument is passed by value (not by reference).

Conclusion:

● Call by Value means the original variable remains unchanged after the
function call.

● It is the default behavior in PHP for passing arguments.

PHP Call by Reference


In PHP, Call by Reference is a mechanism where a function receives a
reference (alias) to the variable instead of a copy. This allows the function to
modify the original variable passed to it.
When a reference is passed to a function, both the original variable and the
reference variable point to the same memory location, meaning any change
made to the reference will reflect on the original variable.

Example: Call by Reference


<?php
$var = "Hello"; // Original variable
$var1 = &$var; // Reference variable

$var1 = "Hello World"; // Change the reference


echo "var=$var var1=$var1" . PHP_EOL; // Both variables show the updated
value

$var = "How are you?"; // Change the original variable


echo "var=$var var1=$var1" . PHP_EOL; // Both variables show the updated
value
?>

Output:
var=Hello World var1=Hello World
var=How are you? var1=How are you?

In the above example:


● $var1 is a reference to $var. Any changes made to $var1 also affect $var
and vice versa.
Calling a PHP Function by Reference
To call a function by reference, you need to declare the function parameters with
the & symbol before the argument name.
function callref(&$arg1, &$arg2) {
// Statements inside the function
}

When you pass variables by reference, any changes inside the function will
directly affect the variables passed.

Example: Calling Function by Reference


<?php
function change_name(&$nm) {
echo "Initially the name is $nm" . PHP_EOL;
$nm = $nm . "_new"; // Modify the reference variable
echo "This function changes the name to $nm" . PHP_EOL;
}

$name = "John";
echo "My name is $name" . PHP_EOL; // Before modification
change_name($name); // Call the function by reference
echo "My name now is $name" . PHP_EOL; // After modification
?>

Output:
My name is John
Initially the name is John
This function changes the name to John_new
My name now is John_new

In this example:
● The $name variable is passed by reference to the change_name()
function.

● Any changes made to $nm inside the function are reflected in $name.

Swapping Two Variables Using Call by Value and Call by Reference


When passing arguments by value, changes inside the function do not affect the
original variables. However, when passing by reference, changes inside the
function are reflected in the original variables.
Call by Value:
<?php
function swap_value($a, $b) {
echo "Initial values a = $a b = $b \n";
$c = $a; $a = $b; $b = $c; // Swap values
echo "Swapped values a = $a b = $b \n";
}

$x = 10; $y = 20;
echo "Actual arguments x = $x y = $y \n\n";

swap_value($x, $y); // Call by value


echo "Actual arguments do not change after the function: \n";
echo "x = $x y = $y \n\n";
?>

Output:
Actual arguments x = 10 y = 20
Initial values a = 10 b = 20
Swapped values a = 20 b = 10
Actual arguments do not change after the function:
x = 10 y = 20

Call by Reference:
<?php
function swap_ref(&$a, &$b) {
echo "Initial values a = $a b = $b \n";
$c = $a; $a = $b; $b = $c; // Swap values
echo "Swapped values a = $a b = $b \n";
}

$x = 10; $y = 20;
echo "Actual arguments x = $x y = $y \n\n";

swap_ref($x, $y); // Call by reference


echo "Actual arguments get changed after the function: \n";
echo "x = $x y = $y";
?>

Output:
Actual arguments x = 10 y = 20
Initial values a = 10 b = 20
Swapped values a = 20 b = 10
Actual arguments get changed after the function:
x = 20 y = 10

In Call by Reference:
● The changes made to $a and $b inside the function are reflected in the
original variables $x and $y.

Return by Reference
In PHP, a function can also return a reference to a variable. To do this, you
need to prefix the return type with &.
Example: Return by Reference
<?php
function &myfunction(){
static $x = 10;
echo "x Inside function: $x \n";
return $x; // Return reference to $x
}

$a = &myfunction(); // Get reference to $x


echo "Returned by Reference: $a \n";
$a = $a + 10; // Modify the reference
$a = &myfunction(); // Get updated reference
?>
Output:
x Inside function: 10
Returned by Reference: 10
x Inside function: 20

In this example:
● The &myfunction() function returns a reference to the static variable $x.

● Modifying the returned reference $a also changes the value of $x since


they both point to the same memory location
Conclusion:
● Call by Reference allows a function to modify the original variable
passed to it, which is not possible with Call by Value.
You can pass variables by reference using & both in function calls and
function return values.

File Handling in PHP


In PHP, file handling refers to managing files on the server—whether it's reading
from or writing to them. PHP offers a set of functions that allow you to handle
files efficiently and allows developers to manage user data, store logs, generate
reports, or even work with configuration files.
What is File Handling?
File handling in PHP involves four main operations:
Opening a File: This allows you to open a file for reading, writing, or appending.

Reading from a File: After opening the file, you can read its contents.

Writing to a File: You can write data into the file (either overwriting or
appending).

Closing a File: It is important to close the file after all the operations are
complete to free up resources.

Why Use File Handling?


File handling is crucial because it helps you:
Store user information securely.

Manage logs for debugging and monitoring.

Create and manage configuration files.

Generate reports for users or administrative purposes.

Opening a File
To open a file in PHP, you use the fopen() function. This function requires two
parameters:
File Path: The path to the file you want to open.

Mode: Specifies how you want to interact with the file (read, write, append,
etc.).

Common File Modes:


"r": Read-only mode (opens the file for reading).

"w": Write-only mode (creates a new file or truncates an existing file).

"a": Append-only mode (opens a file for writing but appends data to the end).

"r+": Read and write mode (opens the file for both reading and writing).

Example of Opening a File:


$file = fopen("/PHP/PhpProjects/myfile.txt", "r");
if ($file) {
echo "File opened successfully!";
} else {
echo "Error opening the file.";
}

Output:
File opened successfully!

Reading from a File


Once a file is opened, you can read its contents using the following functions:
fgets($file): Reads a single line from the file.

fread($file, $length): Reads a specified number of bytes from the file.

Example of Reading a File:


$file = fopen("/PHP/PhpProjects/myfile.txt", "r");

while (($line = fgets($file)) !== false) {


echo $line . "\n";
}

fclose($file);

Output:
Hello this is an example of

PHP File Handling.

Writing to a File
To write data into a file, you need to open it in either "w" or "a" mode. Use the
fwrite() function to write content.
Example of Writing to a File:
$file = fopen("/PHP/PhpProjects/myfile.txt", "a");

if ($file) {
fwrite($file, "\nThis is a new line in the file.\n");
fclose($file);
echo "Data written to the file successfully!";
} else {
echo "Error opening the file.";
}

Output:
Data written to the file successfully!

Updated File Content:


Hello this is an example of

PHP File Handling.

This is a new line in the file.

Closing a File
It is important to close a file after performing operations to release system
resources. Use the fclose() function to close the file once you are done with it.
Example of Closing a File:
$file = fopen("/PHP/PhpProjects/myfile.txt", "r");
// Perform operations
fclose($file);
echo "The file has been closed.";

Output:
The file has been closed.

File Handling Errors


It’s essential to handle errors gracefully when working with files. Always check if
the file has been opened successfully before proceeding with any operations.
Example of Error Handling:
$file = fopen("nonexistent.txt", "r");
if (!$file) {
echo "Error: File does not exist.";
} else {
fclose($file);
}

Output:
Error: File does not exist.

Stream Wrappers in PHP


PHP supports different stream protocols for file handling. Use the
stream_get_wrappers() function to get a list of all registered stream wrappers.
Example:
print_r(stream_get_wrappers());

Output:
Array
(
[0] => php
[1] => file
[2] => glob
[3] => data
[4] => http
[5] => ftp
[6] => zip
[7] => compress.zlib
[8] => compress.bzip2
[9] => https
[10] => ftps
[11] => phar
)

Why Do We Need to Open Files?


Opening files is important for the following reasons:
Retrieve data: For example, reading user submissions.

Save data: For example, saving user-generated content or logs.

Handle file formats: Working with different file formats such as JSON, CSV, or
XML.

Syntax of fopen()
The fopen() function has the following syntax:
fopen(
string $filename,
string $mode,
bool $use_include_path = false,
?resource $context = null
): resource|false

Parameters:
$filename: The name of the file to open.

$mode: The mode to open the file in.

$use_include_path: Optional. Set to true if you want to search for the file in
the include path.

$context: Optional. A stream context resource.

Modes of Opening a File


Mode Description

r Open file for reading only.

w Open file for writing only. Creates a new file or truncates an existing
one.

a Open file in append mode (write only).

r+ Open file for reading and writing.

w+ Open file for reading and writing. Creates a new file or truncates an
existing one.

a+ Open file for reading and writing in append mode.

x Creates a new file for write-only.

x+ Creates a new file for reading and writing.


Example of File Opening in Different Modes:
// Opening a file for writing
$handle = fopen("hello.txt", "w");

// Opening a file for reading


$handle = fopen("http://localhost/hello.txt", "r");

Closing a File
Once you're done reading or writing to the file, always ensure you close it using
fclose($handle) to release system resources.

Absolutely! Here's your comprehensive, professional breakdown of PHP


File Uploading in the same structured format as we did for file handling —
perfect for study, notes, or even presentation slides.

1. Email Basics in PHP – (16 Marks)


🔹 Definition:
PHP allows sending emails using the built-in mail() function. This is commonly
used in web applications to send confirmation emails, alerts, and notifications.

Logic:
1. Collect email data (recipient, subject, message).

2. Use the mail() function to send the email.

3. Provide optional headers for extra information like "From", "Reply-To", etc.

4. Check if the email was successfully sent.

🧾 Syntax:
php
CopyEdit
mail(to, subject, message, headers, parameters);

📄 Example Code (basicmail.php):


php

<?php
$to = "[email protected]"; // Recipient's email
$subject = "Test Email from PHP"; // Subject
$message = "Hello! This is a test email sent using PHP."; // Email
body
$headers = "From: [email protected]"; // Optional header

if (mail($to, $subject, $message, $headers)) {


echo "✅ Email sent successfully!";
} else {
echo "❌ Email sending failed.";
}
?>
Output:
✅ Email sent successfully!
(Note: Will only work on a server with mail service configured, like Sendmail or
SMTP relay.)
Key Points:
● mail() does not work on localhost without a mail server.

● Must configure mail settings in php.ini for full functionality.

● Headers can contain MIME types, HTML support, or reply-to.

Best Practices:
● Validate email with filter_var($email, FILTER_VALIDATE_EMAIL)

● Always include a proper "From" header.

SENDING WITH EMAIL ATTACHMENTS:


● To send an email with mixed content you should set Content-type
header to multipart/mixed. Then text and attachment sections can
be specified within boundaries.
● A boundary is started with two hyphens followed by a unique
number which can not appear in the message part of the email. A
PHP function md5() is used to create a 32 digit hexadecimal number
to create unique number. A final boundary denoting the email's final
section must also end with two hyphens.

<?php

// request variables
$from = $_REQUEST["from"];
$emaila = $_REQUEST["emaila"];
$filea = $_REQUEST["filea"];

if ($filea) {
function mail_attachment ($from , $to, $subject, $message,
$attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type

$start = strrpos($attachment, '/') == -1 ?


strrpos($attachment, '//') : strrpos($attachment, '/')+1;

// Filename that will be used for the file as the attachment


$fileatt_name = substr($attachment, $start,
strlen($attachment));
$email_from = $from; // Who the email is from
$subject = "New Attachment Message";

$email_subject = $subject; // The Subject of the email


$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to

$headers = "From: ".$email_from;


$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

$msg_txt="\n\n You have recieved a new attachment message from


$from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type:
multipart/mixed;\n" . "
boundary=\"{$mime_boundary}\"";

$email_txt .= $msg_txt;

$email_message .= "This is a multi-part message in MIME format.\n\


n" .
"--{$mime_boundary}\n" . "Content-Type:text/html;
charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";

$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\n" . "Content-Type:


{$fileatt_type};\n" .
" name = \"{$fileatt_name}\"\n" . //"Content-Disposition:
attachment;\n" .
//" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding:
"base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";

$ok = mail($email_to, $email_subject, $email_message, $headers);

if($ok) {
echo "File Sent Successfully.";
// delete a file after attachment sent.
unlink($attachment);
} else {
die("Sorry but the email could not be sent. Please go back and try
again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],
'temp/'.basename($_FILES['filea']['name']));

mail_attachment("$from", "[email protected]",
"subject", "message", ("temp/".$_FILES["filea"]["name"]));
}
?>
<html>
<head>
<script language = "javascript" type = "text/javascript">
function CheckData45() {
with(document.filepost) {
if(filea.value ! = "") {
document.getElementById('one').innerText = "Attaching File ...
Please Wait";
}
}
}
</script>
</head>
<body>
<table width = "100%" height = "100%" border = "0"
cellpadding = "0" cellspacing = "0">
<tr>
<td align = "center">
<form name = "filepost" method = "post"
action = "file.php" enctype = "multipart/form-data" id = "file">
<table width = "300" border = "0" cellspacing = "0"
cellpadding = "0">
<tr valign = "bottom">
<td height = "20">Your Name:</td>
</tr>
<tr>
<td><input name = "from" type = "text" id = "from" size =
"30"></td>
</tr>
<tr valign = "bottom">
<td height = "20">Your Email Address:</td>
</tr>
<tr>
<td class = "frmtxt2"><input name = "emaila" type = "text"
id = "emaila" size = "30"></td>
</tr>
<tr>
<td height = "20" valign = "bottom">Attach File:</td>
</tr>
<tr valign = "bottom">
<td valign = "bottom"><input name = "filea" type = "file" id
= "filea" size = "16"></td>
</tr>
<tr>
<td height = "40" valign = "middle">
<input name = "Reset2" type = "reset" id = "Reset2"
value = "Reset">
<input name = "Submit2" type = "submit" value =
"Submit" onClick = "return CheckData45()">
</td>
</tr>
</table>
</form>
<center>
<table width = "400">
<tr>
<td id = "one"></td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>

PHP AND HTML:

<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php

// define variables and set to empty values


$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $class = $course = $subject = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);

// check if e-mail address is well-formed


if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["course"])) {
$course = "";
} else {
$course = test_input($_POST["course"]);
}

if (empty($_POST["class"])) {
$class = "";
} else {
$class = test_input($_POST["class"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}

if (empty($_POST["subject"])) {
$subjectErr = "You must select one or more subjects";
} else {
$subject = $_POST["subject"];
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Absolute Classes Registration Form</h2>
<p><span class = "error">* required field.</span></p>
<form method = "POST" action = "<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Name:</td>
<td>
<input type = "text" name = "name">
<span class = "error">* <?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>E-mail: </td>
<td>
<input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td>Time:</td>
<td>
<input type = "text" name = "course">
<span class = "error"><?php echo $websiteErr;?></span>
</td>
</tr>
<tr>
<td>Classes:</td>
<td><textarea name = "class" rows = "5" cols =
"40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender" value =
"female">Female
<input type = "radio" name = "gender" value = "male">Male
<span class = "error">* <?php echo $genderErr;?></span>
</td>
</tr>
<tr>
<td>Select:</td>
<td>
<select name = "subject[]" size = "4" multiple>
<option value = "C">C</option>
<option value = "Java">Java</option>
<option value = "C#">C#</option>
<option value = "c++">C++</option>
<option value = "PHP">PHP</option>
<option value = "Python">Python</option>
</select>
</td>
</tr>
<tr>
<td>Agree</td>
<td><input type = "checkbox" name = "checked" value =
"1"></td>
<?php if(!isset($_POST['checked'])){ ?>
<span class = "error">* <?php echo "You must agree to
terms";?></span>
<?php } ?>
</tr>
<tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</tr>
</table>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<h2>Your given values are as :</h2>";
echo ("<p><b>Name</b> : $name</p>");
echo ("<p><b>Email address</b> : $email</p>");
echo ("<p><b>Preffered class time</b> : $course</p>");
echo ("<p><b>Class info</b> : $class </p>");
echo ("<p><b>Gender</b> : $gender</p>");
echo "<p><b>Subjcts Chosen:</b><p>";
if (!empty($subject)) {
echo "<ul>";
for($i = 0; $i < count($subject); $i++) {
echo "<li>$subject[$i]</u/li>";
}
echo "</ul>";
}
}
?>
</body>
</html>
Databases with PHP

Databases are essential components for storing, retrieving, and managing


data in web applications. In PHP, the most common database used is
MySQL, but PHP can interact with many types of databases. This section
covers basic interactions with MySQL databases using PHP, including
connecting to the database, retrieving data, inserting data, updating data,
and deleting data.

Here is the complete login system example in PHP using MySQL, with all
the necessary components, formatted as requested with the Verdana font
and a font size of 12:

1. Config.php (Database Connection)


<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'mydb');
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD,
DB_DATABASE);
?>

Explanation:

● This script is responsible for establishing the connection to the


MySQL database using the mysqli API.
● It defines constants for the database server, username, password,
and database name, and then uses these constants to connect to
the database.

2. Login.php (Login Form)


<?php
include("config.php");
session_start();
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// username and password sent from form


$myusername = mysqli_real_escape_string($db, $_POST['username']);
$mypassword = mysqli_real_escape_string($db, $_POST['password']);

$sql = "SELECT * FROM admin WHERE username = '$myusername'


and passcode = '$mypassword'";

$result = mysqli_query($db, $sql);


$count = mysqli_num_rows($result);

if ($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: welcome.php");
} else {
$error = "Your Login Name or Password is invalid";
}
}
?>

<html>
<head>
<title>Login Page</title>
<style type="text/css">
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
}
label {
font-weight: bold;
width: 100px;
font-size: 12px;
}
.box {
border: #666666 solid 1px;
}
</style>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<div style="width: 300px; border: solid 1px #333333;" align="left">
<div style="background-color: #333333; color: #FFFFFF; padding:
3px;"><b>Login</b></div>
<div style="margin: 30px">
<form action="" method="post">
<label>UserName :</label><input type="text"
name="username" class="box" /><br /><br />
<label>Password :</label><input type="password"
name="password" class="box" /><br /><br />
<input type="submit" value="Submit" /><br />
</form>
<div style="font-size: 11px; color: #cc0000; margin-top:
10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>

Explanation:

● The form collects the username and password input from the user.

● When the form is submitted, the username and password are


validated against the admin table in the database. If a match is
found, the user is redirected to welcome.php.

3. Session.php (Session Handling)


<?php
session_start();

if (!isset($_SESSION['login_user'])) {
header("location: login.php");
die();
}
$login_session = $_SESSION['login_user'];
?>

Explanation:
● This script checks if the session variable login_user is set, which
means the user is authenticated.

● If not, the user is redirected to login.php.

4. Welcome.php (Welcome Page)


<?php
include('session.php');
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
<h2><a href="logout.php">Sign Out</a></h2>
</body>
</html>

Explanation:

● This page welcomes the logged-in user by displaying their username


($login_session), which is stored in the session variable.

● A "Sign Out" link is provided to log the user out.

5. Logout.php (Logout Script)


<?php
session_start();

if (session_destroy()) {
header("Location: login.php");
}
?>

Explanation:

● This script destroys the session, effectively logging the user out.

● After logging out, the user is redirected back to the login.php


page.
SQL Script to Create Database and Admin Table
USE mydb;

CREATE TABLE `admin` (


`username` VARCHAR(10) NOT NULL,
`passcode` VARCHAR(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_general_ci;

INSERT INTO `admin` (`username`, `passcode`) VALUES


('guest', 'abc123'),
('manager', 'secret'),
('user', 'test');

ALTER TABLE `admin`


ADD PRIMARY KEY (`username`);
COMMIT;

Explanation:

● This SQL script creates a database called mydb and a table named
admin with two fields: username and passcode.

● It inserts some test data into the table and defines username as the
primary key.

Running the Application

● To run this login system, place all the PHP files (config.php,
login.php, session.php, welcome.php, logout.php) in the htdocs
folder (if using XAMPP).

● Open a browser and visit http://localhost/login.php to test the


login functionality.

Summary

This simple login system in PHP uses MySQL for authentication. The core
steps are:
1. Connecting to the Database: Using mysqli to connect to MySQL.

2. Login Form: Collects username and password and checks if they


match with the data in the database.

3. Session Handling: Uses PHP sessions to manage user


authentication across pages.

4. Welcome Page: Displays a welcome message if the user is


authenticated.

5. Logout: Destroys the session and redirects the user to the login
page.

If the query doesnt fetch any matching row, the error message is
displayed as follows −

Connecting to a MySQL Database

To interact with a MySQL database in PHP, you first need to establish a


connection using the mysqli or PDO extension. We will use mysqli for this
example.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

//Connected successfully

The connect_error property checks if the connection was successful. If


not, the script will terminate with an error message.

Creating a Database

Explanation:
Once connected to the server, we can create a new database using SQL
commands. The mysqli_query() function is used to execute SQL queries.

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to create database


$sql = "CREATE DATABASE test_db";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

//Database created successfully

We use the CREATE DATABASE SQL query to create a new database.

If the database is created successfully, a success message is shown;


otherwise, an error message is displayed.

Creating a Table in the Database


Explanation:
After creating the database, we can create tables to store data. A table is
a structure where data is stored in rows and columns.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to create table


$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";

if ($conn->query($sql) === TRUE) {


echo "Table 'users' created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

//Table 'users' created successfully

● We define the structure of the table using the SQL CREATE TABLE
statement.

● The id field is set as a primary key and will auto-increment with


each new record.

● The firstname, lastname, and email fields are defined as VARCHAR


with appropriate lengths.

Inserting Data into a Database Table


Explanation:
Once a table is created, we can insert data into the table using the
INSERT INTO SQL command.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to insert data


$sql = "INSERT INTO users (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

//New record created successfully

● We use the INSERT INTO SQL statement to add a new record into
the users table.

● The values 'John', 'Doe', and '[email protected]' are inserted


into the respective columns.

Retrieving Data from a Database

Explanation:
We can fetch data from the database using the SELECT SQL query. The
mysqli_query() function is used to execute the query, and
mysqli_fetch_assoc() is used to retrieve the result.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to select data


$sql = "SELECT id, firstname, lastname, email FROM users";
$result = $conn->query($sql);

// Check if there are results


if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " .
$row["lastname"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

//id: 1 - Name: John Doe - Email: [email protected]

The SELECT query retrieves data from the users table.

The while loop iterates through the rows of the result set and displays the
data for each user.

Updating Data in a Database


Explanation:
We can update existing data in the database using the UPDATE SQL query.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to update data


$sql = "UPDATE users SET email='[email protected]' WHERE id=1";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

//Record updated successfully

The UPDATE query modifies the email field for the user with id=1.

The WHERE clause ensures that only the specified record is updated.

Deleting Data from a Database


Explanation:
We can delete data from the database using the DELETE SQL query.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to delete data


$sql = "DELETE FROM users WHERE id=1";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

//Record deleted successfully

The DELETE query removes the record where the id=1 from the users
table.

Here is a concise 5-page summary of the "Server Side Processing and


Scripting" document with key concepts, syntax, code snippets, and
output examples. This includes PHP basics, variables, operators, control
structures, arrays, and functions.

Page 1: Introduction to PHP


What is PHP?

● PHP: Hypertext Preprocessor – server-side scripting language used


for web development.

● Developed by Rasmus Lerdorf in 1994.

● Latest Version: PHP 8.4.3 (Jan 16, 2025).

● Embedded in HTML, supports dynamic pages, session management,


and DB connectivity.

Basic Syntax
<?php
echo "Hello World!";
?>

Output:
Hello World!

PHP Tags

● Standard: <?php ... ?>

● Case-insensitive for keywords (echo, IF, etc.)

<?php
ECHO "Hello<br>";
EcHo "World!<br>";
?>

Output:

Hello
World!

Page 2: Variables and Data Types


Declaring Variables
$name = "John";
$age = 25;
$price = 12.50;

Rules

● Start with $

● Must begin with letter/underscore

● Case-sensitive: $Name ≠ $name

Output Variables
$txt = "W3Schools.com";
echo "I love $txt!";

Output:

I love W3Schools.com!
Variable Types
var_dump(5); // int(5)
var_dump("John"); // string(4) "John"
var_dump(3.14); // float(3.14)
var_dump([2, 3, 56]); // array(3) { ... }

Type Conversion
$x = 10;
$y = "20";
echo $x + $y;

Output:

30

Page 3: Operators in PHP


Arithmetic Operators
$a = 12; $b = 4;
echo $a + $b; // 16
echo $a * $b; // 48

Comparison Operators
$a = 5; $b = "5";
var_dump($a == $b); // true
var_dump($a === $b); // false

Logical Operators
$a = true; $b = false;
var_dump($a && $b); // false
var_dump($a || $b); // true

Assignment Operators
$x = 10;
$x += 5; // $x = 15

String Operators
$first = "Hello";
$second = " World!";
echo $first . $second; // Hello World!

Page 4: Control Structures & Loops


If-Else
$t = 14;
if ($t < 20) echo "Have a good day!";
else echo "Good night!";

Output:

Have a good day!

Switch Statement
$color = "red";
switch ($color) {
case "red": echo "Color is red"; break;
default: echo "Unknown";
}

Output:

Color is red

Loops
For Loop
for ($i = 0; $i < 3; $i++) echo $i . " ";

Output:

012

While Loop
$i = 0;
while ($i < 3) {
echo $i . " ";
$i++;
}
Output:

012

Foreach Loop
$arr = [1, 2, 3];
foreach ($arr as $val) echo $val . " ";

Output:

123

Page 5: Arrays & Functions


Array Types
Indexed Array
$arr = [10, 20, 30];
echo $arr[1]; // 20

Associative Array
$marks = ["John"=>80, "Jane"=>90];
echo $marks["Jane"]; // 90

Multidimensional Array
$students = [["John", 80], ["Jane", 90]];
echo $students[1][1]; // 90

User-defined Functions
function greet($name) {
return "Hello $name";
}
echo greet("John");

Output:

Hello John

Passing by Reference
function addFive(&$val) {
$val += 5;
}
$num = 10;
addFive($num);
echo $num; // 15

Return Type
function add(int $a, int $b): int {
return $a + $b;
}
echo add(5, 10); // 15

Here's the continuation of the structured summary (with code and


output) for your PHP notes from the uploaded document. This covers:

● File Handling

● File Uploading

● Sending Email

● Database Connection and CRUD

Page 6: File Handling in PHP


Opening a File
$file = fopen("/PHP/PhpProjects/myfile.txt", "r");
if ($file) {
echo "File opened successfully!";
} else {
echo "Error opening the file.";
}

Output:

File opened successfully!

Reading from a File


$file = fopen("/PHP/PhpProjects/myfile.txt", "r");
while (($line = fgets($file)) !== false) {
echo $line . "\n";
}
fclose($file);

Output:

Hello this is an example of


PHP File Handling.

Writing to a File
$file = fopen("/PHP/PhpProjects/myfile.txt", "a");
if ($file) {
fwrite($file, "\nThis is a new line in the file.\n");
fclose($file);
echo "Data written to the file successfully!";
}

Output:

Data written to the file successfully!

Error Handling Example


$file = fopen("nonexistent.txt", "r");
if (!$file) {
echo "Error: File does not exist.";
} else {
fclose($file);
}

Output:

Error: File does not exist.

Page 7: File Uploading in PHP


HTML Upload Form
<form action="upload.php" method="post" enctype="multipart/form-
data">
Select file: <input type="file" name="fileToUpload">
<input type="submit" value="Upload File">
</form>
PHP Upload Script (upload.php)
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has
been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}

Output (if successful):

The file example.jpg has been uploaded.

Page 8: Sending Emails with PHP


Basic Email
$to = "[email protected]";
$subject = "Test Email from PHP";
$message = "Hello! This is a test email sent using PHP.";
$headers = "From: [email protected]";

if (mail($to, $subject, $message, $headers)) {


echo "✅ Email sent successfully!";
} else {
echo "❌ Email sending failed.";
}

Output:

✅ Email sent successfully!

⚠ Note: Works only on servers with mail setup (not localhost


without configuration).

Email with Attachment (Conceptual)


● Use multipart/mixed header

● Create MIME boundaries using md5(time())

● Encode file using base64_encode()

● Send using mail() with full body content

Page 9: PHP with MySQL - Database Basics


Connecting to MySQL
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

Output:

Connected successfully

Creating a Table
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30), lastname VARCHAR(30), email VARCHAR(50)
)";
$conn->query($sql);

Output:

Table 'users' created successfully

Inserting Data
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John',
'Doe', '[email protected]')";
$conn->query($sql);

Output:
New record created successfully

Page 10: PHP with MySQL - CRUD Operations


Select Data
$sql = "SELECT id, firstname, lastname, email FROM users";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " - Email: " .
$row["email"] . "<br>";
}

Output:

id: 1 - Name: John - Email: [email protected]

Update Data
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
$conn->query($sql);

Output:

Record updated successfully

Delete Data
$sql = "DELETE FROM users WHERE id=1";
$conn->query($sql);

Output:

Record deleted successfully

This completes your full 10-page structured summary of PHP server-


side processing topics with keywords, syntax, code, and output
examples.

You might also like