Server Side Processing and Scripting
Server Side Processing and Scripting
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 −
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 −
<?php
echo "Hello World!";
?>
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.
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
ECHO "Hello World!<br>"; O/P: Hello World! (3x)
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
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 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.
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;
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.
<?php
$x = 10;
$y = "20";
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.
<?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
<?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
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>
● local
● global
● static
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();
<!DOCTYPE html>
<html>
<body>
EX:02
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
</body></html>
O/P: Variable x inside function is: 5
Variable x outside function is:
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;
}
</body>
</html> O/P: 15
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 −
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.
<?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.
Syntax
define(name, value);
Parameters:
<?php
const MYCAR = "Volvo";
echo MYCAR;
?>
</body>
</html> O/P: Volvo
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);
?>
array(3) {
[0]=>
string(3) "PHP"
[1]=>
string(4) "Java"
[2]=>
string(6) "Python"
}
echo MINSIZE;
echo PHP_EOL;
// same thing as the previous line
echo constant("MINSIZE");
?>
O/P:
50
50
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
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.
● Arithmetic operators
● Assignment operators
● Comparison operators
● Increment/Decrement operators
● Logical operators
● String operators
● Array operators
● Conditional assignment operators
The following table highlights the arithmetic operators that are supported by
PHP. Assume variable "$a" holds 42 and variable "$b" holds 20 −
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";
// 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";
OUTPUT:
1. Basic Arithmetic Operators:
a + b = 16
a-b=8
a * b = 48
a/b=3
a%b=0
3. Floating-Point Numbers:
f1 / f2 = 3.75
f1 * f2 = 15
The following table highlights the comparison operators that are supported by
PHP. Assume variable $a holds 10 and variable $b holds 20, then −
== 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";
2. Identical (===):
bool(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.
PHP CODE:
<?php
echo "PHP LOGICAL OPERATORS DEMO\n\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
2. Logical OR (||):
bool(true)
Same with 'or': bool(true)
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 −
PHP CODE:
<?php
echo "PHP ASSIGNMENT OPERATORS DEMO\n\n";
OUTPUT:
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2; //Hello world!
?>
PHP CODE:
<?php
echo "PHP ARRAY OPERATORS DEMO (Simple Version)\n\n";
// 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";
<?php
// if empty($user) = TRUE, set $status = "anonymous"
echo $status = (empty($user)) ? "anonymous" : "logged in";
echo("<br>");
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:
1. Concatenation: $f . $l
Full Name: John Doe
4. Case Conversion:
Upper: HELLO
Lower: hello
First Letter Capital: Hello
9. String Reversal
strrev() – Reverses a string.
php
$str = "hello";
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
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");
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
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
<?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.
Syntax:
for (initialization; condition; increment) {
// code to be executed;
}
Example:
<?php
$a = 0;
$b = 0;
Output:
At the end of the loop a = 50 and b = 25
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
Syntax:
while (condition) {
// code to be executed;
}
Example:
<?php
$i = 0;
$num = 50;
Output:
Loop stopped at i = 10 and num = 40
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
Example:
<?php
$i = 0;
Output:
Loop stopped at i = 3
Example:
<?php
$array = array(1, 2, 3, 4, 5);
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.
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
)
)
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] ];
?>
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"]
];
<?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)
- PHP arrays are flexible and can hold any data type.
array(4) {
[0]=>
string(1) "a"
[1]=>
int(10)
[2]=>
float(9.99)
[3]=>
bool(true)
}
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);
?>
Syntax:
$arr1 = array("key"=>"value", ...);
$arr2 = ["key"=>"value", ...];
Example:
$arr1 = array(
10=>"hello",
5.75=>"world",
-5=>"foo",
false=>"bar"
);
Using array_search():
<?php
foreach ($capitals as $pair) {
$cap = array_search($pair, $capitals);
echo "Capital of $cap is $capitals[$cap]
";
}
?>
Syntax:
function functionName() {
// code to be executed
}
Example:
function myMessage() {
echo "Hello world!";
}
myMessage(); // Function call
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
Example with two arguments:
familyName("Hege", "1975");
Example:
setHeight(350);
setHeight(); // Uses default 50
Example:
Example:
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num; // Outputs: 7
function sumMyNumbers(...$x) {
$n = 0;
foreach ($x as $num) {
$n += $num;
}
return $n;
}
Example:
Example:
You can specify a different return type from the argument types, but ensure the
return is the correct type:
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:
● 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.
Output:
var=Hello World var1=Hello World
var=How are you? var1=How are you?
When you pass variables by reference, any changes inside the function will
directly affect the variables passed.
$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.
$x = 10; $y = 20;
echo "Actual arguments 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";
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
}
In this example:
● The &myfunction() function returns a reference to the static variable $x.
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.
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.).
"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).
Output:
File opened successfully!
fclose($file);
Output:
Hello this is an example of
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!
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.
Output:
Error: File does not exist.
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
)
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.
$use_include_path: Optional. Set to true if you want to search for the file in
the include path.
w Open file for writing only. Creates a new file or truncates an existing
one.
w+ Open file for reading and writing. Creates a new file or truncates an
existing one.
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.
Logic:
1. Collect email data (recipient, subject, message).
3. Provide optional headers for extra information like "From", "Reply-To", etc.
🧾 Syntax:
php
CopyEdit
mail(to, subject, message, headers, parameters);
<?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
Best Practices:
● Validate email with filter_var($email, FILTER_VALIDATE_EMAIL)
<?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
$email_txt .= $msg_txt;
$data = chunk_split(base64_encode($data));
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>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
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"]);
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
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:
Explanation:
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.
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.
Explanation:
if (session_destroy()) {
header("Location: login.php");
}
?>
Explanation:
● This script destroys the session, effectively logging the user out.
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.
● 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).
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.
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 −
<?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
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);
}
$conn->close();
?>
<?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);
}
$conn->close();
?>
● We define the structure of the table using the SQL CREATE TABLE
statement.
<?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);
}
$conn->close();
?>
● We use the INSERT INTO SQL statement to add a new record into
the users table.
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);
}
$conn->close();
?>
The while loop iterates through the rows of the result set and displays the
data for each user.
<?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);
}
$conn->close();
?>
The UPDATE query modifies the email field for the user with id=1.
The WHERE clause ensures that only the specified record is updated.
<?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);
}
$conn->close();
?>
The DELETE query removes the record where the id=1 from the users
table.
Basic Syntax
<?php
echo "Hello World!";
?>
Output:
Hello World!
PHP Tags
<?php
ECHO "Hello<br>";
EcHo "World!<br>";
?>
Output:
Hello
World!
Rules
● Start with $
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
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!
Output:
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
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
● File Handling
● File Uploading
● Sending Email
Output:
Output:
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:
Output:
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:
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:
Inserting Data
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John',
'Doe', '[email protected]')";
$conn->query($sql);
Output:
New record created successfully
Output:
Update Data
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
$conn->query($sql);
Output:
Delete Data
$sql = "DELETE FROM users WHERE id=1";
$conn->query($sql);
Output: