0% found this document useful (0 votes)
18 views94 pages

504 Web Framework and Services: Unit 1: Core PHP Programming

The document outlines the core concepts of PHP programming, including its role in server-side web development, installation, and basic syntax. It covers data types, operators, control structures, and functions, providing examples for clarity. The content is structured into units that guide learners through the fundamentals of PHP, making it suitable for beginners in web development.

Uploaded by

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

504 Web Framework and Services: Unit 1: Core PHP Programming

The document outlines the core concepts of PHP programming, including its role in server-side web development, installation, and basic syntax. It covers data types, operators, control structures, and functions, providing examples for clarity. The content is structured into units that guide learners through the fundamentals of PHP, making it suitable for beginners in web development.

Uploaded by

Noor Shaikh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

504 Web Framework and Services

Unit 1: Core PHP Programming


1.1 Introduction to PHP
1.1.1 Understanding the role of PHP in server-side web development
1.1.2 History and evolution of PHP
1.1.3 Installation and configuration using XAMPP/WAMP
1.1.4 Setting up the development environment using Visual Studio Code
1.2 Basic PHP Syntax and Variables
1.2.1 PHP script structure and tags
1.2.2 Declaring and using variables and constants
1.2.3 Using echo and print statements
1.2.4 Comments and formatting conventions
1.3 Data Types and Operators
1.3.1 Primitive types: string, int, float, boolean
1.3.2 Arrays and objects
1.3.3 Type casting and type juggling
1.3.4 Operators: arithmetic, logical, comparison, assignment
1.4 Control Structures and Arrays
1.4.1 Conditional statements: if, else, elseif, switch
1.4.2 Looping constructs: for, while, do-while, foreach
1.4.3 Arrays: indexed, associative, multidimensional
1.4.4 Array operations: sort(), asort(), ksort(), array_merge()
1.5 Functions and Form Handling
1.5.1 Creating and invoking user-defined functions
1.5.2 Function parameters and return values
1.5.3 Variable scope: global vs. local
1.5.4 Handling forms with $_GET and $_POST
1.5.5 Basic input validation and sanitization

1.1 Introduction to PHP

1.1.1 Understanding the Role of PHP in Server-Side Web Development

PHP, or Hypertext Preprocessor, is a widely-used open-source scripting language designed


specifically for web development. Unlike HTML, which only controls the structure and presentation
of a webpage, PHP allows developers to write logic that executes on the server side before the
result is sent to the browser.

In a typical web application, PHP handles dynamic tasks like:

 Validating user input


 Interacting with databases (e.g., retrieving or storing data)
 Processing form submissions
 Managing sessions and cookies
 Generating dynamic content (like news feeds, dashboards, or shopping carts)

PHP code is embedded inside HTML and enclosed within special <?php ... ?> tags. When a user
accesses a PHP page, the server processes the PHP code and returns plain HTML to the client’s
browser. The user never sees the PHP code itself.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 1
504 Web Framework and Services

Example:

<html> Output:
<body> Welcome
<h1>Welcome</h1> Today is Wednesday
<?php
echo "Today is " . date("l");
?>
</body>
</html>

This ability to merge HTML with dynamic server-side logic makes PHP a powerful tool for building
interactive and responsive websites.

1.1.2 History and Evolution of PHP

 1994: PHP was created by Rasmus Lerdorf initially as a set of Common Gateway Interface
(CGI) binaries written in the C programming language. It was used to track visits to his
online resume.

 1995: Named "Personal Home Page Tools" (PHP Tools) and released for public use.

 1997: PHP 3 was developed by Zeev Suraski and Andi Gutmans. This version gave PHP its
current name: PHP: Hypertext Preprocessor.

 2000: PHP 4 was powered by the Zend Engine 1.0 and introduced improved performance
and better support for complex applications.

 2004: PHP 5 was released with full support for object-oriented programming, PDO (PHP
Data Objects), and better XML handling.

 2015: PHP 7 introduced massive performance improvements, reduced memory usage, and
added features like type declarations.

 2020–2024: PHP 8.x series introduced JIT (Just-In-Time compilation), named arguments,
attributes, and union types.

Today, PHP powers over 75% of websites that use server-side programming, including platforms
like WordPress, Facebook (originally), Wikipedia, and many e-commerce platforms.

1.1.3 Installation and Configuration Using XAMPP/WAMP

To run PHP locally on your computer, you need a web server (like Apache), a PHP interpreter, and
often a database like MySQL. XAMPP and WAMP are popular software bundles that include all of
these tools.

XAMPP Installation Steps:

1. Download XAMPP from the official site: [Link]

2. Install the downloaded .exe file and follow the installation wizard.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 2
504 Web Framework and Services

3. Once installed, open the XAMPP Control Panel.

4. Start the Apache and MySQL services.

5. PHP files should be placed inside the htdocs directory (default path: C:/xampp/htdocs/).

6. To run a PHP file (e.g., [Link]), type [Link] in your browser.

WAMP Installation Steps:

1. Download WAMP from: [Link]

2. Install and launch WAMP server.

3. Place your files in the www folder (C:/wamp64/www/).

4. Access via browser: [Link]

Tips:

 Make sure no other application (like Skype) is using port 80.

 Always save files with the .php extension.

1.1.4 Setting Up the Development Environment Using Visual Studio Code

Visual Studio Code (VS Code) is a lightweight but powerful source code editor that works well for
PHP development.

Step-by-Step Setup:

1. Download & Install VS Code: Go to [Link] and install the editor.

2. Install PHP Extension:

o Open VS Code.
o Go to the Extensions tab (or press Ctrl+Shift+X).
o Search for "PHP Intelephense" and install it.
3. Set PHP Executable Path:
o Go to File → Preferences → Settings → Search for [Link].
o Set the path to your PHP executable, e.g., C:/xampp/php/[Link].
4. Create a New Project:
o Create a folder for your project.
o Open that folder in VS Code.
o Create a new file with a .php extension.

Example Code in VS Code:

<?php
echo "PHP is configured and working!";
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 3
504 Web Framework and Services

How to Run:

 Save the file in htdocs (XAMPP) or www (WAMP).

 Open your browser and go to [Link]

1.2 Basic PHP Syntax and Variables

1.2.1 PHP Script Structure and Tags

PHP scripts are embedded within HTML documents and are enclosed by special tags that identify
the beginning and end of the PHP code block. A PHP script always starts with <?php and ends with
?>.

Basic Structure:

<?php
// Your PHP code goes here
echo "Hello, PHP!";
?>

We can mix HTML and PHP code in the same file:

<html>
<body>
<h2>My First PHP Page</h2>
<?php
echo "This is executed by PHP.";
?>
</body>
</html>

When this file is opened in a browser through a server like XAMPP/WAMP, only the result of the
PHP code is visible in the browser.

1.2.2 Declaring and Using Variables and Constants

Variables are used to store data such as strings, numbers, or arrays. In PHP, all variables start with
the $ symbol.

<?php
$name = "Twinkle";
$age = 30;
echo "Name: $name, Age: $age";
?>

Constants are similar to variables except that they cannot be changed after they are defined.

<?php
define("PI", 3.14159);

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 4
504 Web Framework and Services

echo PI;
?>

 Variable names are case-sensitive.


 Constants are usually written in uppercase by convention.
1.2.3 Using echo and print Statements
echo and print are both language constructs used to output data to the screen.

echo:

 Can take multiple parameters (although rarely used).


 Does not return a value.
<?php
echo "Hello", " World!";
?>
print:

 Can only take one argument.


 Always returns 1, so it can be used in expressions.

<?php
print "Hello World!";
?>
In most cases, echo is slightly faster than print and more commonly used.

Feature echo print


Return Value No (does not return value) Yes (returns 1 always)
Usage Can output one or more strings Can output only one string
Parentheses Optional Optional
Speed Slightly faster Slightly slower
Example echo "Hello"; print "Hello";
Multiple Params Yes (echo "A", "B";) No

 Use echo when you just want to print values (especially multiple values).
 Use print if you need to return a value (like inside an expression), but it’s rare in practice.
 echo is more commonly used because it is faster and can print multiple values.
 print returns a value (1), which sometimes allows it to be used in expressions.

1.2.4 Comments and Formatting Conventions

Comments are ignored by the PHP engine and are used to explain code.

Single-line comments:

// This is a single-line comment

# This is also a single-line comment

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 5
504 Web Framework and Services

Multi-line comments:

/*

This is a multi-line comment

that spans several lines.

*/

Best Formatting Practices:

 Indent nested code blocks for better readability.


 Use meaningful variable names.
 Add comments to explain complex logic.
 Leave blank lines between logical blocks of code.

1.3 Data Types and Operators

PHP supports a wide variety of data types and operators. Understanding how to use them is
essential for performing calculations, handling logic, and working with values of different types.

1.3.1 Primitive Types: string, int, float, boolean

PHP's basic data types are:

 String: A sequence of characters, enclosed in either single (') or double (") quotes.

 Integer (int): Whole numbers (e.g., 5, -12, 100).

 Float (double): Decimal numbers (e.g., 3.14, -7.2).

 Boolean: Represents true or false.

Example:

<?php
$name = "Twinkle"; // string
$age = 30; // integer
$height = 5.6; // float
$is_student = true; // boolean
echo "Name: $name\n";
echo "Age: $age\n";
echo "Height: $height\n";
echo "Student: $is_student\n";
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 6
504 Web Framework and Services

1.3.2 Arrays and Objects

1. Arrays and objects are advanced types used to store multiple values or define reusable
structures.

Arrays can be:

 Indexed: Accessed by numeric index.

 Associative: Use named keys.

 Multidimensional: Arrays inside arrays.

Example:

<?php
$colors = array("red", "green", "blue"); // Indexed array
$person = array("name" => "Twinkle", "age" => 30); // Associative array
$matrix = array(
array(1, 2),
array(3, 4)
); // Multidimensional array
echo $colors[0]; // red
echo $person["name"]; // Twinkle
echo $matrix[1][1]; // 4
?>

2. Objects are instances of user-defined classes.

<?php
class Car {
public $brand = "Toyota";
}
$myCar = new Car();
echo $myCar->brand; // Toyota
?>

1.3.3 Type Casting and Type Juggling

PHP is a loosely typed language. This means you don't have to declare data types explicitly.
However, PHP may automatically convert data types during execution (type juggling), or you can
convert them manually (type casting).

Type Juggling Example:

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 7
504 Web Framework and Services

<?php
$x = "5";
$y = 10;
$z = $x + $y; // PHP converts "5" to integer 5
echo $z; // 15
?>

Type Casting Example:

<?php
$value = "123.45";
$intVal = (int)$value; // Converts to 123
$floatVal = (float)$value; // Converts to 123.45
echo $intVal; // 123
echo $floatVal; // 123.45
?>

1.3.4 Operators

PHP provides a wide range of operators to perform operations on variables and values.

1. Arithmetic Operators

Arithmetic Operator are as follows:

Operator Name Example Result


+ Addition $a + $b Sum of $a and $b
- Subtraction $a - $b Difference
* Multiplication $a * $b Product
/ Division $a / $b Quotient
% Modulus $a % $b Remainder
** Exponentiation $a ** $b $a raised to $b

Example is as follows:

<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition
echo $a - $b; // Subtraction
echo $a * $b; // Multiplication
echo $a / $b; // Division
echo $a % $b; // Modulus
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 8
504 Web Framework and Services

2. Assignment Operators
Assignment operators are used to assign values to variables. The most common is the
simple equal sign =, but there are several compound assignment operators as well.

Operator Name Example Meaning


= Assignment $a = $b Assigns value of $b to $a
+= Addition Assignment $a += $b $a = $a + $b
-= Subtraction Assignment $a -= $b $a = $a - $b
*= Multiplication Assignment $a *= $b $a = $a * $b
/= Division Assignment $a /= $b $a = $a / $b
%= Modulus Assignment $a %= $b $a = $a % $b
**= Exponentiation Assignment $a **= $b $a = $a ** $b

Example is as follows:

<?php
$x = 5;
$x += 3; // $x becomes 8
$x *= 2; // $x becomes 16
echo $x;
?>

3. Comparison Operators

Comparison operators are used to compare two values or variables. The result is always either
true or false.

Operator Name Example Result/Meaning


== Equal to $a == $b True if $a is equal to $b
=== Identical (equal and same $a === True if $a is equal to $b and same type
type) $b
!= Not equal to $a != $b True if $a is not equal to $b
<> Not equal to (alternate) $a <> $b Same as !=
!== Not identical $a !== $b True if $a is not equal or not the same type
as $b
> Greater than $a > $b True if $a is greater than $b
< Less than $a < $b True if $a is less than $b
>= Greater than or equal to $a >= $b True if $a is greater than or equal to $b
<= Less than or equal to $a <= $b True if $a is less than or equal to $b

Example is as follows:

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 9
504 Web Framework and Services

<?php
$x = 10;
$y = "10";
var_dump($x == $y); // true (value is equal)
var_dump($x === $y); // false (type is not equal)
var_dump($x != $y); // false
?>

4. Logical Operators

Logical operators are used to combine multiple conditions and return either true or false.

Operator Name Example Result/Meaning


&& AND ($a && $b) True if both $a and $b are true
and AND (lower precedence) ($a and $b) Same as && but lower precedence
` ` OR
or OR (lower precedence) ($a or $b) Same as `
! NOT !$a True if $a is not true
xor XOR (exclusive or) ($a xor $b) True if either $a or $b is true, but not both

Example is as follows:

<?php
$a = true;
$b = false;
var_dump($a && $b); // false
var_dump($a || $b); // true
var_dump(!$a); // false
?>

1.4 Control Structures and Arrays

PHP offers control structures that allow developers to control the flow of the script depending on
conditions and looping mechanisms. It also provides flexible array structures for storing multiple
values.

1.4.1 Conditional Statements: if, else, elseif, switch

Conditional statements allow a program to execute different blocks of code depending on the
condition's truth value.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 10
504 Web Framework and Services

if-else Statement:

<?php
$marks = 70;
if ($marks >= 50) {
echo "You passed.";
} else {
echo "You failed.";
}
?>

elseif Ladder:

<?php
$marks = 85;
if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 75) {
echo "Grade B";
} elseif ($marks >= 60) {
echo "Grade C";
} else {
echo "Grade D";
}
?>

switch Statement:

<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Tuesday":
echo "Second day of the week";
break;
default:
echo "Some other day";
}
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 11
504 Web Framework and Services

1.4.2 Looping Constructs: for, while, do-while, foreach

Loops are used to execute a block of code repeatedly under a condition.

1. for loop:

<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
?>

2. while loop:

<?php
$i = 1;
while ($i <= 3) {
echo "Count: $i<br>";
$i++;
}
?>

3. do-while loop:

<?php
$i = 1;
do {
echo "Do count: $i<br>";
$i++;
} while ($i <= 2);
?>

4. foreach loop:

<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "$color<br>";
}
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 12
504 Web Framework and Services

1.4.3 Arrays: Indexed, Associative, Multidimensional

An array is a special variable that can store multiple values in a single variable. In PHP, arrays are
very flexible and can store different types of data (numbers, strings, even other arrays).

1. Indexed Array:

Indexed arrays store data in a sequence, where each element has a numeric index (starting
from 0).

<?php
$names = array("Alice", "Bob", "Charlie");
echo $names[1]; // Outputs: Bob
?>

2. Associative Array:

Associative arrays use named keys (strings) instead of numeric indexes. Each key is linked to a
specific value.

$student = array("name" => "RAM", "age" => 21, "grade" => "A");
echo $student["name"]; // Output: RAM

3. Multidimensional Array:

A multidimensional array is an array of arrays. You can store arrays inside other arrays—
useful for representing tables or complex data.

<?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6)
);
echo $matrix[1][2]; // Outputs: 6

$marks = array(
array(85, 92, 78), // Student 1's marks
array(88, 90, 74), // Student 2's marks
array(90, 70, 80) // Student 3's marks
);
echo $marks[1][2]; // Output: 74 (Student 2's 3rd subject)

?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 13
504 Web Framework and Services

Example with associative and multi-dimensional:

$students = array(
array("name" => "Rahul", "age" => 21, "grade" => "A"),
array("name" => "Priya", "age" => 22, "grade" => "B")
);
echo $students[0]["name"]; // Output: Rahul

Array Type Index Type Example Declaration Access Example


Indexed Array Numeric (0, 1, $arr = array("A", "B", "C"); $arr[1] // "B"
2…)
Associative Array Named keys $arr = array("name"=>"John", $arr["age"] // 20
"age"=>20);
Multidimensional Arrays within See above example $arr[1][2] or
array $arr[0]["name"]

1.4.4 Array Operations: sort(), asort(), ksort(), array_merge()

PHP provides built-in functions to operate on arrays.

1. sort(): Sorts indexed arrays in ascending order

<?php
$fruits = array("Banana", "Apple", "Cherry");
sort($fruits);
print_r($fruits);
?>

2. asort(): Sorts associative arrays by value

<?php
$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
asort($ages);
print_r($ages);
?>

3. ksort(): Sorts associative arrays by key

<?php
ksort($ages);
print_r($ages);
?>

4. array_merge(): Merges two arrays

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 14
504 Web Framework and Services

<?php
$array1 = array("a", "b");
$array2 = array("c", "d");
$result = array_merge($array1, $array2);
print_r($result);
?>

1.5 Functions and Form Handling

Functions are reusable blocks of code that perform a specific task. They help avoid code repetition
and make the code easier to manage.

1.5.1 Creating and Invoking User-Defined Functions

A function is defined using the function keyword followed by the function name and a pair of
parentheses. You can call the function anywhere in your script after it is defined.

function greet() {
echo "Hello, welcome to PHP functions!";
}
greet();

1.5.2 Function Parameters and Return Values

Functions can accept input values (called parameters) and can return values back to the calling
code using the return statement.

<?php
function add($a, $b) {
return $a + $b;
}
$sum = add(5, 10);
echo "Sum: $sum";
?>

Assigning default values to parameters:

<?php
function greetUser($name = "Guest") {
echo "Hello, $name!";
}
greetUser("Twinkle");
greetUser(); // Uses default
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 15
504 Web Framework and Services

1.5.3 Variable Scope: Global vs. Local

Variable Scope

Variable scope means where a variable can be accessed or used in your PHP script.

1. Local Variables

A local variable is declared inside a function and can only be accessed within that
function. Outside the function, it does not exist.

function test() {
$x = 10; // local variable
echo $x; // Works here
}
test(); // Output: 10
echo $x; // Error! $x is undefined outside the function

2. Global Variables

A global variable is declared outside any function and can be accessed from anywhere in
the script—but NOT directly inside functions.

 To use a global variable inside a function, you must declare it as global inside the
function using the global keyword.

$y = 20; // global variable

function show() {
// echo $y; // Error! $y is not accessible directly
global $y; // Makes $y accessible
echo $y; // Output: 20
}

show(); // Output: 20

echo $y; // Output: 20 (outside function)

<?php
$x = 5;
function display() {
global $x;
echo $x; // 5
}
display();

?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 16
504 Web Framework and Services

Difference Between Local & Global Variable

Feature Local Variable Global Variable


Where Inside a function Outside all functions
declared
Accessible in Only within the function Anywhere in the script (but needs global
where declared keyword inside functions)
Lifetime Exists only during function Exists as long as the script runs
execution
Keyword None global keyword required inside functions
needed
Default access Not accessible outside the Not accessible inside functions by default
function
Example function test() { $a = 10; } $a = 10; (outside any function)
Example function show() { $b = 20;
usage $a = 10; // local function display() {
echo $a; // works global $b; // required to use $b
} echo $b; // works
}

1.5.4 Handling Forms with $_GET and $_POST

 GET and POST are two of the most common HTTP methods used to transfer data between a
client (browser) and a server (website).
 They define how form data is sent from an HTML page to a server-side script (such as
PHP).

The GET Method

 When a form uses method="get", the browser appends the form data to the URL as query
parameters.
 Example URL after submission:
[Link]
 The data is visible in the browser’s address bar.

How to Access Data in PHP:

 Use the $_GET superglobal array to access form data.

$name = $_GET['name'];

$age = $_GET['age'];

Advantages

1. Simple to Use: Easy to implement for data retrieval.


2. Visible Data: Data appears in the URL, making debugging easy.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 17
504 Web Framework and Services

3. Bookmarkable: URLs can be bookmarked and shared easily.


4. Cacheable: Browsers and proxies can cache GET requests, improving speed for repeated
access.
5. Supports Hyperlinks: Can be used in links (anchor tags), not just forms.
6. Good for Idempotent Actions: Safe for actions that do not modify data (like search/filter).

Disadvantages

1. Limited Data Length: Most browsers limit URL length (about 2048 characters).
2. Not Secure: Data is visible in the URL, so it’s not safe for sensitive information (passwords,
personal data).
3. Data Exposed: GET requests can be logged in browser history and server logs.
4. No File Uploads: Cannot be used to upload files.
5. Limited Use Cases: Not suitable for submitting large amounts of data or changing data on
the server.

The POST Method

 When a form uses method="post", the browser sends form data in the HTTP request body.
 The URL remains clean—no data appears in the address bar.

How to Access Data in PHP:

 Use the $_POST superglobal array to access form data.

$name = $_POST['name'];
$age = $_POST['age'];

Advantages

1. More Secure: Data is sent in the request body, not visible in the URL.
2. No Data Length Limit: Can send large amounts of data (only limited by server
configuration).
3. Supports File Uploads: Suitable for uploading files (e.g., images, documents).
4. Better for Sensitive Data: Safer for sending passwords and confidential information.
5. Not Cached or Bookmarked: POST requests are not cached by browsers or saved in
history.

Disadvantages

1. Cannot Bookmark: POST data is not saved in URLs, so you cannot bookmark or share form
submissions.
2. Harder to Debug: Data is not visible in the URL, making debugging a bit more complex.
3. No Caching: POST requests are not cached, so repeated submissions can be slower.
4. Not Idempotent: Submitting the same POST request multiple times can cause duplicate
actions (e.g., multiple form submissions).
5. Slightly More Complex: Implementation for file upload and data retrieval is a bit more
complex compared to GET.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 18
504 Web Framework and Services

In summary:

 GET is for fetching data, POST is for sending or updating data.


 Data in GET is visible and limited; data in POST is hidden and unlimited.

PHP can collect form data sent through HTML forms using the global arrays $_GET and
$_POST.

HTML Form:

<form method="post" action="[Link]">


Name: <input type="text" name="username">
<input type="submit">
</form>
[Link]:

<?php
$name = $_POST['username'];
echo "Welcome, $name!";
?>

 Use method="post" for secure and large data submission.


 Use $_GET when data is sent via URL parameters (e.g., search queries).

Basic Form with GET method:

<form method="get" action="[Link]">


Search: <input type="text" name="query">
<input type="submit">
</form>

[Link]:

<?php
$search = $_GET['query'];
echo "You searched for: $search";
?>

Difference Between GET & POST

Feature GET POST


How Data is Data is sent in the URL (visible) Data is sent in the request body
Sent (hidden)
Visibility Visible to everyone (appears in Not visible in the URL
address bar)
Data Length Limited (usually up to 2048 No restrictions (large amounts
characters) allowed)

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 19
504 Web Framework and Services

Use Case For fetching or retrieving data only For sending, updating, or submitting
data
Security Less secure (data is exposed in URL) More secure (data not visible in URL)
Bookmarking Can be bookmarked and cached Cannot be bookmarked or cached
Idempotency Safe for repeat use (does not change Not idempotent (can change data on
data) server)
Form Example <form method="get"> <form method="post">

Difference Between ECHO, PRINT & PRINT_R

Feature echo print print_r


Type Language construct Language construct Function
Return Value No (does not return Yes (returns 1) Yes (returns value
a value) or outputs)
Usage Outputs one or Outputs a single string Outputs human-
more strings readable info
Multiple Yes (echo "A", "B";) No (print "A";) No
Params
Best For Simple Simple strings/HTML output, Debugging
strings/HTML can be used in expressions arrays/objects
output
Array/Object Cannot output Cannot output arrays/objects Can output
Output arrays/objects arrays/objects
Parentheses Optional Optional Required (as
function)

1.5.5 Basic Input Validation and Sanitization

When building web applications, you often collect data from users through forms (like login,
registration, feedback, etc.). However, user input can be incorrect, incomplete, or even
malicious (harmful). To prevent errors and protect your application, it is essential to validate and
sanitize all user inputs before processing or saving them.

Input Validation

 Input validation is the process of checking if the input provided by the user is correct,
complete, and in the expected format.
 It helps ensure data quality and prevents incorrect data from entering your system.

Input Validation filters check if the data is in the correct format.

1. FILTER_VALIDATE_INT — Checks for a valid integer.


2. FILTER_VALIDATE_FLOAT — Checks for a valid floating-point number.
3. FILTER_VALIDATE_BOOLEAN — Checks for a valid boolean value.
4. FILTER_VALIDATE_EMAIL — Checks for a valid email address.
5. FILTER_VALIDATE_URL — Checks for a valid URL.
6. FILTER_VALIDATE_IP — Checks for a valid IP address.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 20
504 Web Framework and Services

Examples of Validation:

 Checking if a required field (like “Name”) is not left blank.


 Ensuring an email field contains a valid email address (like user@[Link]).
 Making sure the age field contains only numbers and is within a certain range (e.g., 1-120).

Input Sanitization

 Sanitization means cleaning the input to remove or neutralize unwanted or potentially


dangerous data (like HTML tags, special characters, or script code).
 This step is crucial to prevent security threats like Cross-Site Scripting (XSS) or SQL
Injection.

Sanitization filters clean the data, removing or encoding unwanted characters.

1. FILTER_SANITIZE_EMAIL — Removes illegal characters from an email address.


2. FILTER_SANITIZE_URL — Removes illegal characters from a URL.
3. FILTER_SANITIZE_NUMBER_INT — Removes all characters except digits, plus and minus
sign.
4. FILTER_SANITIZE_SPECIAL_CHARS — Converts special HTML characters to HTML
entities.
5. FILTER_SANITIZE_FULL_SPECIAL_CHARS — Converts all special characters to HTML
entities (more strict and secure, preferred in PHP 8+).

Examples of Sanitization:

 Removing HTML tags from comments or messages.


 Escaping special characters before saving data to a database.
 Stripping unwanted spaces from user input.

Why are Validation and Sanitization Important?

 Prevents errors caused by invalid data.


 Protects your application from common web attacks.
 Ensures your application only works with safe and clean data.

How to Perform Input Validation and Sanitization in PHP

1. Using PHP’s Built-in Functions

a. Validation Example:

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 21
504 Web Framework and Services

$name = $_POST['name'];
if (empty($name)) {
echo "Name is required.";
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
}

b. Sanitization Example:

// Remove extra spaces and HTML tags


$name = trim($_POST['name']);
$name = strip_tags($name);
// Sanitize email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

2. Combining Validation and Sanitization

It’s common to sanitize first, then validate:

$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid email.";
}

Common PHP Functions for Validation and Sanitization

Function Purpose
empty() Checks if a variable is empty
is_numeric() Checks if input is a number
filter_var() Validates/sanitizes various data types
trim() Removes whitespace from input
strip_tags() Removes HTML tags from a string
htmlspecialchars() Converts special characters to HTML

Simple Example: Validating and Sanitizing a Form

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 22
504 Web Framework and Services

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$name = strip_tags($name);
if (empty($name)) {
echo "Name is required.";
} else {
echo "Hello, " . htmlspecialchars($name);
}
}

Difference Between Validation and Sanitization

Feature Validation Sanitization


Purpose To check if data is in the correct format To clean data by removing or
and meets requirements escaping unwanted or dangerous
characters
When Used After receiving input, before processing Before saving, displaying, or using the
or storing it data anywhere
What It Does Confirms data is correct, complete, and Modifies data to make it safe and
as expected acceptable
Result Pass (valid) or Fail (invalid) Returns a safe, cleaned version of the
input
Example Checking if an email is valid Removing HTML tags or special
characters from a name
Common filter_var($x, strip_tags($x), htmlspecialchars($x),
Functions FILTER_VALIDATE_EMAIL), trim($x)
is_numeric()

Example

Validation : Checks if the email is in a proper format.

$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address!";
}

Sanitization: Removes HTML tags and extra spaces to make the input safe.

$name = $_POST['name'];
$name = strip_tags($name);
$name = trim($name);

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 23
504 Web Framework and Services

EXAMPLE OF STUDENT REGISTRATION FORM

HTML CODE

<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Age: <input type="number" name="age" min="10" max="100"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" name="register" value="Register">
</form>

// WRITE PHP CODE FOR VALIDATION HERE

</body>
</html>

PHP CODE

<?php
$error = [];
$success = "";

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {


// Sanitize inputs
$name = trim(strip_tags($_POST['name']));
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
$age = trim($_POST['age']);
$gender = $_POST['gender'] ?? '';
$password = $_POST['password'];

// Validation
if (empty($name)) {
$error[] = "Name is required.";
} elseif (strlen($name) < 3) {
$error[] = "Name must be at least 3 characters.";
}

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 24
504 Web Framework and Services

if (empty($email)) {
$error[] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "Invalid email format.";
}

if (empty($age)) {
$error[] = "Age is required.";
} elseif (!is_numeric($age) || $age < 10 || $age > 100) {
$error[] = "Age must be a number between 10 and 100.";
}

if (empty($gender)) {
$error[] = "Please select gender.";
}

if (empty($password)) {
$error[] = "Password is required.";
} elseif (strlen($password) < 6) {
$error[] = "Password must be at least 6 characters.";
}

// If no errors
if (empty($error)) {
// Here you can add database insert code or further processing.
$success = "Registration successful!";
// Optionally clear form values
$_POST = [];
}
}

// Display errors
if (!empty($error)) {
echo '<div class="error">'.implode('<br>', $error).'</div>';
}

// Display success message


if ($success) {
echo '<div class="success">'.$success.'</div>';
}
?>

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 25
504 Web Framework and Services

ASSIGNMENT FOR PRACTICE

Multiple Choice Questions [1 Marks Each]

1. PHP stands for:


o a) Personal Home Page
o b) Private Home Page
o c) PHP: Hypertext Preprocessor
o d) Preprocessor Home Page
Answer: c) PHP: Hypertext Preprocessor
2. Which of the following is the correct way to start a PHP block?
o a) <php>
o b) <?php ?>
o c) <script>
o d) <?php?>
Answer: b) <?php ?>
3. Which function is used to output text in PHP?
o a) print()
o b) echo
o c) write()
o d) display()
Answer: b) echo
4. Which symbol is used to declare a variable in PHP?
o a) #
o b) &
o c) $
o d) %
Answer: c) $
5. Which of the following is a valid variable name in PHP?
o a) 1variable
o b) _variable
o c) $variable-name
o d) variable name
Answer: b) _variable

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 26
504 Web Framework and Services

6. What will be the output of echo 2 + "2"; in PHP?


o a) 22
o b) 4
o c) Error
o d) "2"+"2"
Answer: b) 4
7. Which superglobal is used to collect form data sent with method="post"?
o a) $_GET
o b) $_POST
o c) $_FORM
o d) $_DATA
Answer: b) $_POST
8. How can you write a single-line comment in PHP?
o a) // comment
o b) # comment
o c) /* comment */
o d) Both a and b
Answer: d) Both a and b
9. What is the correct way to end a statement in PHP?
o a) .
o b) :
o c) ;
o d) ,
Answer: c) ;
10. Which operator is used to concatenate two strings in PHP?
o a) +
o b) &
o c) .
o d) ,
Answer: c) .

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 27
504 Web Framework and Services

Long Questions [5 Marks Each]

1. Explain the role of PHP in server-side web development with examples.


2. Describe the steps to install and configure XAMPP/WAMP for PHP development.
3. Discuss the difference between echo, print, and print_r in PHP with suitable examples.
4. Explain the different types of variables in PHP and their usage.
5. Write a PHP script to accept two numbers from the user and display their sum, difference,
and product.
6. Describe the concept of arrays in PHP. Explain with examples of indexed, associative, and
multidimensional arrays.
7. Write a PHP program to validate a simple registration form (name, email, password) and
display appropriate messages.
8. Explain the concept of variable scope in PHP (local vs global) with examples.
9. List and explain any five important built-in functions used in PHP.
10. Discuss the difference between GET and POST methods in form handling with suitable code
snippets.

Educator: Asst. Prof. Twinkle Panchal


Sutex Bank College Of Computer Applications And Science, Amroli Page 28
Unit 2: Advanced PHP and File Management

2.1 File Handling and Directories


2.1.1 Including files using include and require
2.1.2 File operations: fopen(), fread(), fwrite(), fclose()
2.1.3 File upload using $_FILES and move_uploaded_file()
2.1.4 File download using PHP headers
2.1.5 Directory operations: opendir(), readdir(), mkdir(), rmdir()
2.2 Forms, Filters, and JSON
2.2.1 Designing and handling HTML forms
2.2.2 Server-side validation techniques
2.2.3 PHP filters: filter_var() and constants
2.2.4 Parsing and generating JSON with json_encode() and json_decode()
2.3 Cookies, Sessions, and Emails
2.3.1 Creating and accessing cookies using setcookie() and $_COOKIE
2.3.2 Session management with session_start() and $_SESSION
2.3.3 Sending emails using the mail() function
2.3.4 Email formatting: headers, subject, attachments
2.4 OOP and Exception Handling in PHP
2.4.1 Creating classes and objects
2.4.2 Using constructors and property visibility
2.4.3 Inheritance and method overriding
2.4.4 Exception handling: try, catch, finally, throw
2.4.5 Input validation using regular expressions

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 1


Unit 2: Advanced PHP and File Management

2.1.1 Including Files using include and require

In PHP, when developing large-scale applications or websites, it is common to reuse common code (like
headers, footers, menus, or database connections) in multiple pages. To avoid rewriting the same code again
and again, PHP offers two built-in functions:

1. include()
2. require()

Both are used to insert the content of one PHP file into another PHP file before the server executes it.

Purpose and Benefits

 Code Reusability: Allows you to write code once (like menus, headers, configuration, database
connections) and use it in multiple files.
 Easier Maintenance: Updates made in the included file are reflected everywhere it is used.
 Organization: Breaks large PHP scripts into smaller, manageable files.

Example: Using include

File Structure:
project/
├── [Link]
└── [Link]

[Link]

<h1>Welcome to My Website</h1>
<hr>

[Link]

<?php
include("[Link]");
echo "<p>This is the main content of the homepage.</p>";
?>

Output:
Welcome to My Website
----------------------
This is the main content of the homepage.

If the file is missing, a warning is shown but the script continues.

Example: Using require

File Structure:
project/
├── [Link]
└── [Link]

[Link]

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 2


Unit 2: Advanced PHP and File Management

<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "student_db";
?>

[Link]

<?php
require("[Link]");
echo "<h2>Connecting to database at $db_host</h2>";
?>

If the file is missing, a fatal error occurs and the script stops.

Example: Using require_once

require_once ensures the file is included only once, even if called multiple times.

Example:
<?php
require_once("[Link]");
require_once("[Link]"); // This will not be included again
?>

Comparison Table

Function Error Type if File Execution Behavior Use Case


Missing
include Warning Script continues Optional files (e.g., sidebar,
footer)
require Fatal Error Script stops Essential files (e.g., config,
DB connect)
require_once Fatal Error Script stops (but only loads Prevent duplicate loading
once) of essential files

 include: If the file is missing, PHP gives a warning but the script continues running.
 require: If the file is missing, PHP gives a fatal error and stops the script immediately.
 include_once/require_once: Used when a file should only be included once (prevents redeclaration
errors).

2.1.2 File Operations: fopen(), fread(), fwrite(), fclose()

File handling is an essential part of web development that allows a PHP script to interact with files — such as
creating, reading, writing, and closing text or data files stored on the server.

PHP provides a simple set of functions for file operations:

 fopen() – to open a file


 fread() – to read from a file

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 3


Unit 2: Advanced PHP and File Management

 fwrite() – to write to a file


 fclose() – to close a file

Working with Files in PHP

To manipulate files (read/write):

1. Open the file using fopen()


2. Read or write using fread() or fwrite()
3. Close the file using fclose()

Opening a File (fopen)

$handle = fopen("[Link]", "r"); // Open for reading only

Parameters:

 1st: Filename (string)


 2nd: Mode (string)

Common File Modes:

Mode Purpose File Created if Not Exists?


"r" Read only No
"w" Write only, truncate to zero Yes
"a" Append only, to the end Yes
"r+" Read and write (start of file) No
"a+" Read and append Yes

Reading from a File (fread)

$handle = fopen("[Link]", "r");


$content = fread($handle, filesize("[Link]")); // Reads the whole file
echo $content;
fclose($handle);

Writing to a File (fwrite)

$handle = fopen("[Link]", "w");


fwrite($handle, "Hello, this is a file write example.");
fclose($handle);

Note: Using "w" mode will overwrite existing content.

Appending to a File

$handle = fopen("[Link]", "a");


fwrite($handle, "\nThis line will be added at the end.");
fclose($handle);

Closing a File (fclose): Always close files after finishing:

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 4


Unit 2: Advanced PHP and File Management

fclose($handle);

This frees up system resources.

Error Handling: Always check if file open was successful:

$handle = fopen("[Link]", "r");


if ($handle) {
// operations...
fclose($handle);
} else {
echo "Unable to open file!";

Example: Writing and Reading a File

// Writing to file
$file = fopen("[Link]", "w");
fwrite($file, "PHP is powerful!");
fclose($file);

// Reading from file


$file = fopen("[Link]", "r");
$data = fread($file, filesize("[Link]"));
echo $data;
fclose($file);

Output:

PHP is powerful!

Error Handling (Optional):

$file = fopen("[Link]", "r") or die("Unable to open file!");

If the file is not found, it shows: "Unable to open file!"

 Always validate file paths before using fopen() to avoid path traversal attacks.
 Ensure file permissions are properly set (e.g., chmod in Linux).
 Avoid overwriting sensitive files accidentally using w mode.

2.1.3 File Upload Using $_FILES and move_uploaded_file()

File upload is a common feature in web applications. PHP provides a built-in superglobal array called $_FILES
to handle file uploads securely and efficiently. The uploaded file is temporarily stored on the server, and we
use move_uploaded_file() to move it to a permanent location.

It allows users to select and send files from their local computer to your web server.

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 5


Unit 2: Advanced PHP and File Management

HTML Form Example

<form action="[Link]" method="post" enctype="multipart/form-data">


<input type="file" name="student_photo" required>
<input type="submit" value="Upload">
</form>

 Important: enctype="multipart/form-data" is necessary for file uploads.

PHP Script Example

if (isset($_FILES['student_photo'])) {
$file = $_FILES['student_photo'];
$name = $file['name'];
$tmp = $file['tmp_name'];
$size = $file['size'];
$error = $file['error'];
// Optional: Validate file type and size
$allowed = array('jpg', 'jpeg', 'png', 'pdf');
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
echo "Invalid file type!";
exit;
}
if ($size > 2*1024*1024) { // 2MB max
echo "File too large!";
exit;
}
// Move file from temporary to 'uploads/' directory
if (move_uploaded_file($tmp, "uploads/" . $name)) {
echo "File uploaded successfully!";
} else {
echo "File upload failed!";
}
}

Key points:

 $_FILES['student_photo']['tmp_name'] is the temp file location on server.


 move_uploaded_file() actually moves it to the desired folder.

1. HTML Form (Client Side)

<form action="[Link]" method="post" enctype="multipart/form-data">


<label>Select File:</label>
<input type="file" name="myfile">
<input type="submit" value="Upload">
</form>

The attribute enctype="multipart/form-data" is mandatory for file uploads.

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 6


Unit 2: Advanced PHP and File Management

2. PHP Script (Server Side)

<?php
if ($_FILES["myfile"]["error"] == 0) {
$temp = $_FILES["myfile"]["tmp_name"];
$name = $_FILES["myfile"]["name"];
move_uploaded_file($temp, "uploads/" . $name);
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
?>

 $_FILES["myfile"]: Refers to the uploaded file.


 $_FILES["myfile"]["tmp_name"]: Temporary file location.
 $_FILES["myfile"]["name"]: Original name of the uploaded file.
 move_uploaded_file(): Moves the uploaded file from temp folder to a specified location.
 "uploads/" . $name: Stores the file in the "uploads" folder (create it manually if needed).

Common $_FILES Array Keys

Key Meaning
name Original name of uploaded file
type MIME type (e.g., image/jpeg, text/plain)
tmp_name Temporary file location on server
error Error code (0 = success)
size Size of file in bytes

Example with File Type and Size Validation

<?php

$allowedTypes = ['image/jpeg', 'image/png'];

$maxSize = 2 * 1024 * 1024; // 2 MB

if ($_FILES["myfile"]["error"] == 0)
{
if (in_array($_FILES["myfile"]["type"], $allowedTypes) && $_FILES["myfile"]["size"] <= $maxSize)
{
move_uploaded_file($_FILES["myfile"]["tmp_name"], "uploads/" . $_FILES["myfile"]["name"]);
echo "Upload successful!";
}
else
{
echo "Invalid file type or size too large.";
}
}
else
{
echo "Upload error.";
}
?>

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 7


Unit 2: Advanced PHP and File Management

2.1.4 File Download Using PHP Headers

In PHP, you can allow users to download files (PDFs, images, text files, etc.) directly from the server by
sending special HTTP headers. This is especially useful when you want the browser to download the file
instead of displaying it. Purpose of Headers in File Download

Normally, if you link to a file (like a PDF or image), the browser may open it instead of downloading it. To force
a download, we use headers like:

 Content-Type
 Content-Disposition
 Content-Length (optional)
 readfile() to send file content

Basic PHP Script to Download a File

<?php

$file = "documents/[Link]"; // Path to file

// Set headers

header("Content-Type: application/pdf");

header("Content-Disposition: attachment; filename=\"[Link]\"");

header("Content-Length: " . filesize($file));

// Output file to browser

readfile($file);

exit;

?>

Explanation of Code

Line Function
header("Content-Type: application/pdf") Tells browser the type of file (PDF)
header("Content-Disposition: attachment; Forces browser to download the file
filename=...")
header("Content-Length: ...") Optional: Sends file size for progress bar
readfile() Reads the file and sends its content to the browser
exit; Stops further PHP execution after file is sent

MIME Types for Common File Format

File Type MIME Type


PDF application/pdf

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 8


Unit 2: Advanced PHP and File Management

ZIP application/zip
JPG Image image/jpeg
PNG Image image/png
Word Doc application/msword
Excel Sheet application/[Link]-excel
Text File text/plain

Downloading a TXT File

<?php
$file = "files/[Link]";

header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"[Link]\"");
readfile($file);
?>

2.1.5 Directory Operations: opendir(), readdir(), mkdir(), rmdir()

Directory operations in PHP allow developers to create, read, and delete folders (directories) on the server.
This is useful for:

 Organizing uploaded files


 Managing user folders
 Browsing files for galleries or backups

PHP provides several built-in functions for handling directories:

Function Purpose / Description Syntax / Example Notes


mkdir() Creates a new directory mkdir("student_data"); Optional parameters: mode,
recursive. E.g. mkdir("photos",
0777, true);
0777 gives full read/write/execute
permissions.
rmdir() Removes an empty rmdir("student_data"); Will fail if the directory is not empty.
directory
opendir() Opens a directory handle $handle = Used with readdir() to loop through
for reading opendir("myfolder"); contents.
readdir() Reads the next file/folder $entry = Returns false at end. Ignores . and ..
name from opened readdir($handle); for clean listing.
directory
closedir() Closes an opened closedir($handle); Always close the directory after
directory handle reading to free system resources.

2.2 Forms, Filters, and JSON

2.2.1 Designing and Handling HTML Forms

 An HTML form is a section on a web page that allows users to input data and submit it to a server for
processing.
 Forms are commonly used for user registration, login, surveys, feedback, uploads, and more.
EDUCATOR:ASST PROF TWINKLE S. PANCHAL 9
Unit 2: Advanced PHP and File Management

Basic HTML Form Structure

<form action="[Link]" method="post">


<label>Name: <input type="text" name="username" required></label><br>
<label>Email: <input type="email" name="email" required></label><br>
<input type="submit" value="Submit">
</form>

 action: The PHP file that will process the form ([Link] here).
 method: post or get. POST is preferred for sensitive data.
 name: Attribute used to access data in PHP.

Accessing Form Data in PHP

 POST Method:
 $name = $_POST['username'];
 $email = $_POST['email'];
 GET Method:
 $name = $_GET['username'];
 $email = $_GET['email'];

File Upload Form Example

<form action="[Link]" method="post" enctype="multipart/form-data">


<input type="file" name="profilePic">
<input type="submit" value="Upload">
</form>

 enctype="multipart/form-data" is required for file uploads.

Difference Between GET & POST method

Feature GET Method POST Method


Data Visibility Appended in URL (visible) Not visible in URL (sent in HTTP body)
Data Length Limit Limited (approx. 2048 characters) Practically unlimited
Security Less secure (data exposed in URL) More secure (data hidden from URL)
Use Case Used for search, bookmarking, links Used for login, registration, file upload, etc.
Form Syntax <form method="get"> <form method="post">
Access in PHP $_GET['name'] $_POST['name']
Bookmark URL Yes No
Caching Data can be cached in browser Data not cached
Back Button Support Retains form data on back button Form resubmission warning on back button
File Upload Support Not suitable Required for file upload

2.2.2 Server-Side Validation Techniques

Server-side validation is the process of checking and verifying form input on the server, after the data is
submitted by the user. It is implemented using server-side languages like PHP, Python, or Java.

Even if client-side validation (JavaScript) is used, server-side validation is essential for security and data
integrity.

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 10


Unit 2: Advanced PHP and File Management

Reasons for Using Server-Side Validation

Reason Explanation
1. Security Client-side validation can be easily bypassed by disabling JavaScript or modifying
browser code. Server-side validation ensures that malicious users cannot inject
harmful data, such as SQL injections, XSS attacks, etc.
2. Data Integrity Validates data before storing in the database. Prevents invalid, incomplete, or
unexpected data from corrupting the system.
3. Works in All Some users may have JavaScript disabled or unsupported browsers. Server-side
Browsers validation is browser-independent.
4. Reliable and Since validation is done on the server, it can enforce the same rules across different
Centralized pages, devices, and platforms.
5. Validation of Complex checks (e.g., checking if username already exists in DB) can only be done
Business Logic on the server using PHP or SQL.
6. Protection Bots can submit forms without using browsers. Server-side validation prevents
Against Spam or fake submissions.
Bots

Regular Expression

 A regular expression (regex) is a pattern used to match and validate strings.


 To validate email, phone numbers, usernames, etc.
 To search and extract information from strings.

1. preg_match()- Checks if a pattern matches a string (only the first match is considered).

Syntax: preg_match(pattern, input_string, matches);

 pattern: Regular expression (e.g., /[a-z]/)


 input_string: String to be tested
 matches: (optional) Array that stores matched content

Below is a table of commonly used symbols in preg_match() with descriptions and examples:

Symbol Meaning / Description Example Matches Example


Pattern
. Any single character except newline gr.y gray, grey
^ Start of string ^Hello Matches strings starting with
"Hello"
$ End of string world$ Matches strings ending with
"world"
[] Character class (any one character [aeiou] Matches any vowel
inside)
[^] Negated character class (any char not [^0-9] Any character except a digit
inside)
` ` Alternation (OR) `cat
() Grouping (php)+ Matches one or more repetitions of
"php"
{} Quantifier: Exact number of [0-9]{3} Matches exactly 3 digits
repetitions
* 0 or more occurrences a* "", a, aa, aaa
+ 1 or more occurrences a+ a, aa, aaa

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 11


Unit 2: Advanced PHP and File Management

? 0 or 1 occurrence (optional) colou?r color or colour


\ Escape character \. Matches a literal dot .
\d Digit (same as [0-9]) \d{2} Matches two digits like 25
\D Non-digit (same as [^0-9]) \D Matches a, B, !, etc.
\w Word character (letters, digits, \w+ hello123, user_1
underscore)
\W Non-word character \W @, #, space
\s Whitespace (space, tab, newline) \s Matches space or tab
\S Non-whitespace character \S Matches A, 1, @, etc.

Examples

1. Validate Email (custom pattern):

$email = "user@[Link]";
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i", $email)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}

2. Validate Mobile Number (10 digits):

$mobile = "9876543210";
if (preg_match("/^[0-9]{10}$/", $mobile)) {
echo "Valid Mobile Number";
} else {
echo "Invalid";
}

3. Only Letters and Spaces (Name):

$name = "RAM CHANDRA";


if (preg_match("/^[a-zA-Z ]*$/", $name)) {
echo "Valid Name";
} else {
echo "Invalid";
}

4. Example

<?php
$text = "I am learning PHP.";
if (preg_match("/PHP/", $text)) {
echo "The text contains 'PHP'.";
} else {
echo "The text does not contain 'PHP'.";
}
?>

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 12


Unit 2: Advanced PHP and File Management

Output: The text contains 'PHP'.

5. Example

<?php
$text = "My roll number is 45.";
if (preg_match("/\d+/", $text, $match)) {
echo "First number found: " . $match[0];
}
?>

Output: First number found: 45

2. preg_match_all()- Match All Occurrences

<?php
$text = "Marks are 45, 67 and 89.";
preg_match_all("/\d+/", $text, $matches);
print_r($matches[0]);
?>

Output: Array ( [0] => 45 [1] => 67 [2] => 89 )

3. preg_replace() – Replace all spaces in a sentence with hyphens.

<?php

$text = "PHP is fun and powerful.";

$new_text = preg_replace("/\s+/", "-", $text);

echo $new_text;

?>

Output: PHP-is-fun-and-powerful.

<?php
$text = "My phone number is 9876543210";
$newText = preg_replace("/\d/", "#", $text);
echo $newText;
?>

Output: My phone number is ##########

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 13


Unit 2: Advanced PHP and File Management

2.2.3 PHP Filters: filter_var() and Constants

What is filter_var()?

 A built-in PHP function for both validating and sanitizing user input in a secure and consistent way.

Validation & Sanitization

Validation is the process of checking whether input data is correct, complete, and in the expected
format. It is an essential part of form processing in PHP, used to ensure that user-provided data is:

 Valid (e.g., an email has @ and .com)


 Safe (e.g., only numbers in a phone number field)
 Required (e.g., name must not be empty)

Filter Constant Description Example Use


FILTER_VALIDATE_BOOLEAN Validates as a boolean filter_var("true",
(true/false) FILTER_VALIDATE_BOOLEAN)
FILTER_VALIDATE_EMAIL Validates if value is a valid email filter_var("abc@[Link]",
address FILTER_VALIDATE_EMAIL)
FILTER_VALIDATE_FLOAT Validates if value is a float filter_var("3.14",
(decimal) FILTER_VALIDATE_FLOAT)
FILTER_VALIDATE_INT Validates if value is an integer filter_var("100",
FILTER_VALIDATE_INT)
FILTER_VALIDATE_IP Validates if value is a valid IP filter_var("[Link]",
address (IPv4/IPv6) FILTER_VALIDATE_IP)
FILTER_VALIDATE_MAC Validates a MAC address filter_var("00:0a:95:9d:68:16",
FILTER_VALIDATE_MAC)
FILTER_VALIDATE_REGEXP Validates with a custom regular filter_var("abc",
expression FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"
/^[a-z]+$/")))
FILTER_VALIDATE_URL Validates if value is a valid URL filter_var("[Link]
FILTER_VALIDATE_URL)

Example

$email = "user@@[Link]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Email is valid";
} else {
echo "Email is NOT valid";
}

Sanitization in PHP means cleaning or filtering input data by removing unwanted or potentially
harmful characters. It helps protect your application from security risks like:

 Cross-site scripting (XSS)


 HTML/JavaScript injection
 Invalid data formats

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 14


Unit 2: Advanced PHP and File Management

Unlike validation (which checks if the data is correct), sanitization modifies the data to make it safe.

Filter Constant Description Example Input Result


FILTER_SANITIZ Removes tags and special <b>Hello</b> Hello
E_STRING characters
FILTER_SANITIZ Removes invalid characters for user@@exam!![Link] user@[Link]
E_EMAIL an email m
FILTER_SANITIZ Removes illegal URL characters [Link] [Link]
E_URL m
FILTER_SANITIZ Keeps digits and plus/minus Phone: +91-98765 +9198765
E_NUMBER_INT signs only
FILTER_SANITIZ Removes invalid characters for 123.45abc 123.45
E_NUMBER_FLO floats
AT
FILTER_SANITIZ Escapes HTML characters like <, <script>alert('x')</sc &lt;script&gt;alert('x')&lt;/
E_SPECIAL_CHA > ript> script&gt;
RS

Example 1: Sanitize an Email

$email = "user@@exam!![Link]";
$sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $sanitized; // Output: user@[Link]

Example 2: Sanitize URL

$url = "[Link]
$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);
echo $sanitized_url; // Output: [Link]

Difference Between Validation and Sanitization

Feature Validation Sanitization


Purpose Check if data is valid Clean/modify data to make it safe
Example Is this a valid email? Remove bad characters from email
Returns Boolean (true/false) Modified (cleaned) data

2.2.4 Parsing and Generating JSON with json_encode() and json_decode()

 JSON (JavaScript Object Notation) is a lightweight, text-based data format.


 Used for data exchange between servers and web apps (e.g., AJAX, REST APIs).
 PHP uses JSON to store and exchange data in a readable, structured way (arrays, objects).
 PHP uses JSON for integration with JavaScript-based frontends or other services.

Converting PHP Array to JSON (json_encode)

$student = [
"name" => "RAM",
"roll" => 21,
"marks" => [75, 80, 90]
];

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 15


Unit 2: Advanced PHP and File Management

$json = json_encode($student);
echo $json;

// Output: {"name":"RAM","roll":21,"marks":[75,80,90]}

Converting JSON to PHP Array/Object (json_decode)

$json = '{"name":"RAM","roll":21,"marks":[75,80,90]}';
$array = json_decode($json, true); // true: returns associative array
print_r($array);

Output:

Array
(
[name] => RAM
[roll] => 21
[marks] => Array ( [0] => 75 [1] => 80 [2] => 90 )
)

$obj = json_decode($json); // returns stdClass object


echo $obj->name;

Output: RAM

2.3 Cookies, Sessions, and Emails

2.3.1 Creating and Accessing Cookies using setcookie() and $_COOKIE

 A cookie is a small piece of data that a server asks the browser to store. The browser sends it back to
the server with future requests.
 Common uses: remembering usernames, theme preferences, shopping cart info, etc.

Creating a Cookie

Syntax:

setcookie(name, value, expiry, path)

 name: The name of the cookie ("username")


 value: The value to store ("Twinkle")
 expiry: Timestamp for expiry (here, 7 days from now)
 path: The path on the server where the cookie is available ("/" = whole domain)

Set a Cookie

setcookie("username", "RAM", time() + (86400 * 7), "/");

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 16


Unit 2: Advanced PHP and File Management

Accessing a Cookie

if (isset($_COOKIE['username'])) {
echo "Hello, " . $_COOKIE['username'];
} else {
echo "Cookie is not set!";
}

Deleting a Cookie

 Set the expiry to a time in the past:

setcookie("username", "", time() - 3600, "/");

Key Points

 Cookies are stored on the client (browser), not the server.


 Cookie values can be modified by the user—do not store sensitive information.
 Cookies are sent with every HTTP request to the server.

2.3.2 Session Management with session_start() and $_SESSION

 A session stores data on the server about a user's interaction with a website.
 Each user is given a unique session ID (stored in a cookie by default).
 Used for: login systems, shopping carts, maintaining state across pages.

Starting a Session

session_start(); // Must be at the very top of your PHP script!

Storing Data in a Session

$_SESSION['user'] = "RAM";
$_SESSION['role'] = "admin";

Accessing Session Data

session_start();
echo $_SESSION['user']; // Outputs: RAM

Destroying a Session

session_start();
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session

Key Points

 Sessions are more secure than cookies (data is stored on the server).
 Session data is accessible on any page after session_start().

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 17


Unit 2: Advanced PHP and File Management

 Sessions expire after a period of inactivity or when destroyed.

2.3.3 Sending Emails using the mail() Function

Purpose

 PHP’s mail() function lets you send emails directly from your server.

Basic Syntax

$to = "student@[Link]";
$subject = "Welcome to PHP!";
$message = "Hello, this is a test email from PHP.";
$headers = "From: admin@[Link]";
if (mail($to, $subject, $message, $headers)) {
echo "Mail sent!";
} else {
echo "Mail failed!";
}

 $to: Recipient’s email address


 $subject: Subject line of the email
 $message: Email content
 $headers: Additional headers (From, CC, BCC, etc.)

Important Notes

 mail() may not work on local XAMPP/WAMP unless configured with a mail server.
 For real-world use, SMTP-based libraries like PHPMailer or SwiftMailer are recommended for
reliability and security.

2.3.4 Email Formatting: Headers, Subject, Attachments

Custom Email Headers

 Control sender, reply-to, CC, BCC, content type, etc.

$headers = "From: admin@[Link]\r\n";


$headers .= "Reply-To: help@[Link]\r\n";
$headers .= "CC: manager@[Link]\r\n";
$headers .= "BCC: auditor@[Link]\r\n";
$headers .= "Content-type: text/html\r\n";

HTML Emails

 To send HTML-formatted emails, set the correct content-type header:

$headers = "MIME-Version: 1.0\r\n";


$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: admin@[Link]\r\n";

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 18


Unit 2: Advanced PHP and File Management

Example:

$message = "<h1>Welcome!</h1><p>This is an HTML email.</p>";


mail($to, $subject, $message, $headers);

Sending Attachments (Advanced)

 The native mail() function can send attachments, but it’s complicated.
 For practical use, PHPMailer or similar libraries are preferred.

PHPMailer Example (Basic):

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer();


$mail->setFrom('from@[Link]', 'Your Name');
$mail->addAddress('to@[Link]');
$mail->Subject = 'Here is your file';
$mail->Body = 'Please see the attached file.';
$mail->addAttachment('/path/to/[Link]');
$mail->send();

 PHPMailer supports attachments, HTML, authentication, and much more.

Applications

 Cookies: Remembering "Keep me logged in" settings, last-visited pages, shopping cart for guests.
 Sessions: User authentication, storing user profile info, multi-page forms.
 Emails: Sending welcome messages, password resets, OTPs, newsletters, receipts.

2.4 OOP and Exception Handling in PHP

2.4.1 Creating Classes and Objects

What is OOP?

 OOP (Object-Oriented Programming) is a programming paradigm based on the concept of "objects",


which are data structures containing data (properties) and code (methods).

Advantages of OOP

Benefit Description
Reusability Use the same class in multiple projects
Modularity Code is organized into logical classes
Scalability Easy to update and expand code
Security Encapsulation hides internal details
Real-world modeling Programs are easier to design and understand

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 19


Unit 2: Advanced PHP and File Management

Basic Concepts of OOP in PHP

Concept Description
Class Blueprint for objects (template)
Object Instance of a class
Property Variable inside a class
Method Function inside a class
Constructor Special method that runs when object is created
Inheritance One class can inherit properties and methods from another
Encapsulation Hiding internal data using private, protected, public
Polymorphism Same method behaves differently in different classes

Access Modifiers

Modifier Description
public Accessible from anywhere
private Accessible only within the class
protected Accessible within class and its subclasses

Declaring a Class

class Student {
// Properties (attributes)
public $name;
public $roll;
// Methods (functions)
public function displayInfo() {
echo "Name: $this->name, Roll: $this->roll";
}
}

Creating an Object

// Create object (instance) of class


$stud1 = new Student();
$stud1->name = "RAM";
$stud1->roll = 21;
$stud1->displayInfo();
// Output: Name:RAM, Roll: 21

Key Points

 $this refers to the current object instance.


 Properties and methods are accessed using -> operator.

2.4.2 Using Constructors and Property Visibility

Constructors

 A constructor is a special method that runs automatically when an object is created.

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 20


Unit 2: Advanced PHP and File Management

 In PHP, the constructor is named __construct().

Example:
class Student {
public $name;
public $roll;
public function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
}
public function displayInfo() {
echo "Name: $this->name, Roll: $this->roll";
}
}
$stud1 = new Student("RAM", 21);
$stud1->displayInfo();

Property Visibility

 public: Accessible from anywhere.


 protected: Accessible only within the class and its subclasses.
 private: Accessible only within the class itself.

Example:

class Demo {
public $x = 1; // Accessible anywhere
protected $y = 2; // Accessible in class and subclasses
private $z = 3; // Accessible only in this class
public function showAll() {
echo "$this->x, $this->y, $this->z";
}
}

2.4.3 Inheritance and Method Overriding

Inheritance

Inheritance allows a class (child/subclass) to acquire properties and methods from another class
(parent/superclass).

Example:

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 21


Unit 2: Advanced PHP and File Management

class Animal {
public function makeSound() {
echo "Animal sound<br>";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark!<br>";
}
}

$d = new Dog();
$d->makeSound(); // Output: Bark!

 Dog inherits from Animal, and overrides the makeSound method.

Accessing Parent Methods

class ParentClass {
public function greet() {
echo "Hello from Parent";
}
}
class ChildClass extends ParentClass {
public function greet() {
parent::greet();
echo " and Child";
}
}
$obj = new ChildClass();
$obj->greet(); // Output: Hello from Parent and Child

2.4.4 Exception Handling: try, catch, finally, throw

An exception is an error that disrupts the normal flow of a program. Instead of crashing the program, PHP
allows us to handle exceptions gracefully using special keywords

PHP Exception Handling Keywords

1. try: Used to wrap the code that may cause an exception.

2. catch: Used to handle the exception if thrown inside the try block.

3. throw: Used to manually throw an exception.

4. finally: (Optional) Always executes, whether an exception was thrown or not — used for cleanup code.

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 22


Unit 2: Advanced PHP and File Management

Exception Handling Syntax

try {

// Code that may cause an exception

} catch (Exception $e) {

// Code that handles the exception

} finally {

// Optional: Code that always runs

Built In Exception

Exception Class Inherited From Use Case Example


Exception Base class General-purpose exception
InvalidArgumentException LogicException Function argument validation
DivisionByZeroError ArithmeticError Divide by zero operations
TypeError Error Wrong type in function argument
ParseError Error Syntax error in eval() code
ErrorException Exception Convert PHP errors into catchable exceptions

Example:

<?php

function squareRoot($num)
{
if ($num < 0) {
throw new InvalidArgumentException("Number must be non-negative");
}
return sqrt($num);
}
try
{
echo squareRoot(-9);
}
catch (InvalidArgumentException $e)
{
echo "Error: " . $e->getMessage();
}
?>

Output: Error: Number must be non-negative

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 23


Unit 2: Advanced PHP and File Management

Custom Exception Example: Divide By Zero

<?php

function divide($a, $b)


{
if ($b == 0) {
throw new Exception("Division by zero is not allowed.");
}
return $a / $b;
}

try
{
echo divide(10, 0);
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
finally
{
echo " - Division attempted.";
}

?>

EDUCATOR:ASST PROF TWINKLE S. PANCHAL 24


CHAPTER 3 CODEIGNITER FRAMEWORK

3.3.1 Installing and Configuring CodeIgniter (CI4)


CodeIgniter 4 (CI4) is a modern, open-source PHP framework that provides a simple and
elegant toolkit for building dynamic web applications. It is designed to be fast, lightweight, and
easy to use, while still offering advanced features such as security, database management, and
MVC (Model–View–Controller) architecture.

The framework is particularly popular among students, educators, and professional


developers because of its clear documentation, minimal configuration requirements, and high
performance.

Key Highlights of CI4:

 Lightweight and high-speed execution.


 Supports PHP 7.4 and PHP 8.x.
 Offers built-in security measures (CSRF, XSS protection, input validation).
 Supports MVC for better code organization.
 Easy integration with databases and external libraries.

2. History of CodeIgniter

Early Development (2006 – 2013)

 2006: CodeIgniter was first developed by Rick Ellis, the founder of EllisLab, to power
their product ExpressionEngine (a content management system).
 The aim was to create a fast, lightweight, and developer-friendly PHP framework with
minimal configuration compared to bulky frameworks of that time.
 CodeIgniter 1.x and 2.x gained popularity for their speed and small size, making them
the go-to choice for many PHP developers.

Transition to British Columbia Institute of Technology (2014)

 In 2014, EllisLab announced they would no longer actively develop CodeIgniter.


 The British Columbia Institute of Technology (BCIT) took over its maintenance to
ensure the framework remained open source and freely available.
 BCIT maintained CodeIgniter 3.x, which became a stable and reliable version used in
many projects.

The Arrival of CodeIgniter 4 (2020 – Present)

 2015 – 2019: The core team began working on a complete rewrite of CodeIgniter to
match modern PHP standards.
 February 24, 2020: CodeIgniter 4.0.0 was officially released.
 CI4 was not just an update — it was a full redesign using:
o Namespaces

EDUCATOR: ASST PROF TWINKLE PANCHAL 1


CHAPTER 3 CODEIGNITER FRAMEWORK

o Composer support
o PSR (PHP Standards Recommendations) compliance
 CI4 is now maintained actively by the CodeIgniter Foundation with frequent updates
for security, performance, and feature enhancements.

3. Evolution Summary Table

Version Release Key Features Maintained By


Year
CodeIgniter 2006 Lightweight core, simple MVC EllisLab
1.x
CodeIgniter 2011 Improved security, Active Record EllisLab
2.x updates
CodeIgniter 2015 Stability, PHP 5.6+ support, extended BCIT
3.x libraries
CodeIgniter 2020 PHP 7.4/8+, Composer, Namespaces, CodeIgniter
4.x PSR compliance Foundation

[Link] Features of CodeIgniter 4


CodeIgniter 4 is a modern PHP framework designed to help developers build web applications
quickly, efficiently, and with cleaner code organization. Its architecture, built-in features, and
compatibility with the latest PHP versions make it a popular choice among developers. Below is
a detailed discussion of its key features.

1. Lightweight and Fast

 Minimal Footprint:
CodeIgniter 4 is built to be small in size, meaning it does not require heavy dependencies
or large libraries to function. The core system is compact and easy to install, often just a
few megabytes in size.
 High Performance:
Because of its minimal architecture, applications run faster and consume fewer server
resources. This is particularly useful for hosting environments with limited memory or
processing capacity.
 Optimized Execution:
The framework is designed to execute only what is necessary for the current request,
reducing overhead and improving response time.
 Practical Example:
If you are building a small-to-medium web application like an online booking system,
CodeIgniter can handle thousands of requests with lower server load compared to bulkier
frameworks.

2. MVC Support (Model–View–Controller)

EDUCATOR: ASST PROF TWINKLE PANCHAL 2


CHAPTER 3 CODEIGNITER FRAMEWORK

 Clear Code Separation:


CodeIgniter follows the MVC design pattern, which organizes application logic into three
separate layers:
o Model: Handles data operations (database queries, data validation, data
manipulation).
o View: Manages the user interface (HTML templates, CSS styling, user output).
o Controller: Connects Models and Views, handling user input and deciding what
to display.
 Advantages:
o Easier maintenance — changes in the View do not affect the Model logic.
o Better teamwork — front-end and back-end developers can work independently.
 Real-Life Example:
In an e-commerce site, the Model would manage product data from the database, the
View would display product pages, and the Controller would process the request when a
user adds an item to the cart.

3. Security

 CSRF Protection (Cross-Site Request Forgery):


Protects forms from unauthorized submissions by including unique security tokens with
each form submission.
 XSS Filtering (Cross-Site Scripting):
Automatically filters malicious scripts from user inputs to prevent hacking attempts.
 Input Validation:
Provides built-in validation methods to ensure only clean, safe, and expected data is
processed.
 Password Handling:
Supports PHP’s password hashing functions to store passwords securely.
 Example:
If a login form receives <script>alert('hacked')</script> as input, CodeIgniter
automatically cleans it, preventing the script from executing.

4. Built-in Libraries

 Predefined Helpers and Libraries:


CodeIgniter includes ready-made classes for common tasks such as:
o Database Management: Query building, connection handling, and CRUD
operations.
o Session Management: Storing temporary user data securely.
o Form Handling: Generating forms, validating inputs, and managing submissions.
 Advantages:
Saves development time since common functionalities don’t need to be written from
scratch.

EDUCATOR: ASST PROF TWINKLE PANCHAL 3


CHAPTER 3 CODEIGNITER FRAMEWORK

 Example:
Instead of manually writing code to upload a file, developers can use the File Upload
library to handle file selection, type validation, and storage automatically.

5. Modern PHP Support

 PHP 7.4 & PHP 8.x Compatibility:


CodeIgniter 4 is built to take full advantage of new PHP features such as:
o Type hinting
o Nullable types
o Arrow functions
o Enhanced performance from the PHP JIT compiler (in PHP 8+)
 Future-Ready:
Continuous updates ensure that CodeIgniter stays compatible with new PHP releases.
 Example:
Developers can use strict type declarations in function parameters, making code more
reliable and reducing bugs.

Feature Description Benefit


Lightweight & Fast Small core system, quick response Ideal for resource-limited
times hosting
MVC Support Separation of logic, UI, and data Easier maintenance & teamwork
Security CSRF, XSS, validation, hashing Protects from common web
attacks
Built-in Libraries Pre-made helpers for common tasks Faster development
Modern PHP Compatible with PHP 7.4 & 8.x Uses latest PHP features
Support

CodeIgniter folder structure.

The CodeIgniter folder structure is given below:

 application: This directory will have your application logic. All of your application codes will
be held in this directory. Internal subdirectories in the CodeIgniter directory structure are given
below:

 cache – It stores cached files.


 config – It keeps configuration files.
 controller – All application controllers are defined under this controller.
 core – It consists of custom core classes that extend system files. For example, if you
create a base controller that other controllers should extend, then you should place it
under this directory.
 helpers – This directory will be used for user-defined helper functions.
 hooks – It is used for custom hooks in the CodeIgniter folder structure.

EDUCATOR: ASST PROF TWINKLE PANCHAL 4


CHAPTER 3 CODEIGNITER FRAMEWORK

 language – It is used to store language files for applications that use multiple languages.
 libraries – It is used to store custom-created libraries.
 logs – Application log files are placed in this directory.
 models - All application models must be defined under this directory.
 third_party – This is used for custom many packages that are created by you or other
developers.
 views – application views will be stored in this directory.

 system: It consists of the framework core files. It is not advised to make any modifications in
this directory or put your own application code into this directory. System subdirectories in
CodeIgniter are given below:

 core – This is considered to be the heart of the CodeIgniter Framework. All of the core
files that construct the framework are located here. If you would like to extend the core
file functionality, then you must
 create a custom core file in the application directory. After this, you are allowed to
override or add new behavior that you wish. You should never make any changes directly
in this directory.
 database – It stores the files such as database drivers, cache, and other files that are
needed for database operations.
 fonts – This directory contains fonts and font-related information.
 helpers – This directory consists of helper functions that come out of the box.
 language – It contains language files that are used by the framework
 libraries – It contains the source files for the different libraries that come along with
CodeIgniter out of the box.

 user_guide: This directory consists of a user manual for CodeIgniter. You should not upload this
directory during application deployment.
 vendor: This directory consists of composer packages source code.
The [Link] and [Link] are the other two files related to this directory.
 [Link]: This is considered as the entry point into the application. It is placed inside the root
directory.

Code Igniter Application Flow Chart


The following graphic illustrates how data flows throughout the system:

EDUCATOR: ASST PROF TWINKLE PANCHAL 5


CHAPTER 3 CODEIGNITER FRAMEWORK

1. The [Link] serves as the front controller, initializing the base resources needed to run
CodeIgniter.
2. The Router examines the HTTP request to determine what should be done with it.
3. If a cache file exists, it is sent directly to the browser, bypassing the normal system
execution.
4. Security. Before the application controller is loaded, the HTTP request and any user
submitted data is filtered for security.
5. The Controller loads the model, core libraries, helpers, and any other resources needed to
process the specific request.
6. The finalized View is rendered then sent to the web browser to be seen. If caching is
enabled, the view is cached first so that on subsequent requests it can be served.

[Link] System Requirements

Before installing CodeIgniter 4, ensure the following requirements are met:

 PHP Version: PHP 7.4 or higher (PHP 8.x recommended)


 Web Server: Apache or Nginx (XAMPP includes Apache)
 Database: MySQL / MariaDB (optional for static projects)
 Composer: Required for recommended installation method
 PHP Extensions: intl, mbstring, json, curl, xml, gd

Note: If the application displays an error such as “The framework needs the following
extension(s) installed and loaded: intl”, enable it in the [Link] file by removing the semicolon
(;) before extension=intl and restart Apache.

[Link] Installing CodeIgniter 4

A) Installation Using Composer (Recommended Method)

1. Open the Command Prompt


2. Navigate to the Server Directory (XAMPP default: C:\xampp\htdocs)
3. Run the Composer Command:
4. composer create-project codeigniter4/appstarter ci4app

EDUCATOR: ASST PROF TWINKLE PANCHAL 6


CHAPTER 3 CODEIGNITER FRAMEWORK

5. Navigate to the Project Folder:


6. cd ci4app

B) Manual Download Method

1. Download the latest CodeIgniter 4 ZIP from [Link]


2. Extract the contents into the server directory (e.g., C:\xampp\htdocs\ci4app).
3. Access the project via the public folder.

[Link] Running the Application

[Link]

If installed correctly, the CodeIgniter Welcome Page will appear.

[Link] Folder Structure Overview


 app/ → Application code (Controllers, Models, Views, Config).
 public/ → Web root ([Link], assets like CSS/JS).
 system/ → Core framework files (should not be edited).
 writable/ → Logs, cache, uploaded files.
 tests/ → Automated test files.

[Link] Configuring CodeIgniter 4

A) Base URL and Environment

1. Rename env file in the project root to .env.


2. Open .env and configure:
3. CI_ENVIRONMENT = development
4. [Link] = '[Link]

B) Database Configuration

In .env, set:

[Link] = localhost
[Link] = my_database
[Link] = root
[Link] =
[Link] = MySQLi

[Link] Creating a Simple Program in CodeIgniter 4


EDUCATOR: ASST PROF TWINKLE PANCHAL 7
CHAPTER 3 CODEIGNITER FRAMEWORK

Step 1: Create a Controller


app/Controllers/[Link]

<?php

namespace App\Controllers;

class Hello extends BaseController


{
public function index()
{
return "Hello, CodeIgniter!";
}
}

Step 2: Define a Route


app/Config/[Link]

$routes->get('hello', 'Hello::index');

Step 3: Run the Application


Visit:

[Link]

The message “Hello, CodeIgniter!” should appear.

[Link] Common Errors and Solutions

Error Cause Solution


intl extension intl not enabled in Edit [Link] → remove ; before extension=intl
required PHP → restart Apache
404 Not Found Incorrect route or Check [Link] and .env
Base URL
Permission Writable folder access Give write permissions to writable/ folder
Denied issues

3.3.2 Understanding MVC Architecture in CodeIgniter


CodeIgniter is built on the Model–View–Controller (MVC) architectural pattern.
MVC is one of the most popular software design patterns for web applications because it
separates the application’s logic, data, and presentation into three interconnected
components: Model, View, and Controller.

EDUCATOR: ASST PROF TWINKLE PANCHAL 8


CHAPTER 3 CODEIGNITER FRAMEWORK

From a technical and architectural standpoint, CodeIgniter was created with the following
objectives:

 Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed


only when requested, rather than globally. No assumptions are made by the system
regarding what may be needed beyond the minimal core resources, so the system is very
light-weight by default. The events, as triggered by the HTTP request, and the controllers
and views you design will determine what is invoked.
 Loose Coupling. Coupling is the degree to which components of a system rely on each
other. The less components depend on each other the more reusable and flexible the
system becomes. Our goal was a very loosely coupled system.
 Component Singularity. Singularity is the degree to which components have a narrowly
focused purpose. In CodeIgniter, each class and its functions are highly autonomous in
order to allow maximum usefulness.

CodeIgniter is a dynamically instantiated, loosely coupled system with high component


singularity. It strives for simplicity, flexibility, and high performance in a small footprint
package.

CODEIGNITER MVC STRUCTURE

This separation provides:

 Better code organization


 Easier maintenance
 Parallel development (multiple developers can work on different layers)
 Improved scalability (easy to add new features)

[Link] The MVC Concept

EDUCATOR: ASST PROF TWINKLE PANCHAL 9


CHAPTER 3 CODEIGNITER FRAMEWORK

1. Model

The Model represents the data layer of the application.


It is responsible for:

 Interacting with the database.


 Defining the structure of data.
 Performing data operations such as create, read, update, and delete (CRUD).
 Applying business rules for data.

Example:
If you are building a Student Management System, the Model file [Link] may
contain functions like getStudents(), addStudent(), updateStudent(), and deleteStudent().

In CodeIgniter:

 Models are stored in app/Models/.


 Typically extend the CodeIgniter\Model class.

2. View

The View is the presentation layer.


It is responsible for:

 Displaying the data to the user.


 Generating HTML, CSS, and JavaScript for the browser.
 Showing the results processed by the Controller.

Example:
In the Student Management System, the student_list.php view displays a table of all students.

In CodeIgniter:

 Views are stored in app/Views/.


 Views do not contain complex logic, only minimal PHP for displaying variables.

3. Controller

The Controller is the application logic layer.


It is responsible for:

 Handling incoming requests from the browser.


 Calling the appropriate Model to get or manipulate data.
 Choosing the correct View to display results.
 Acting as the “middleman” between Model and View.

EDUCATOR: ASST PROF TWINKLE PANCHAL 10


CHAPTER 3 CODEIGNITER FRAMEWORK

Example:
In the Student Management System, the [Link] controller may handle routes like
/students, fetch student data from the Model, and send it to a View.

In CodeIgniter:

 Controllers are stored in app/Controllers/.


 Extend the BaseController class by default.

[Link] MVC Workflow in CodeIgniter

The flow of execution in an MVC application in CodeIgniter can be explained step-by-step:

1. User Request
A user accesses a URL (e.g., [Link]
2. Routing
CodeIgniter’s routing system (defined in app/Config/[Link]) decides which
Controller and method should handle the request.
3. Controller Processing
The selected Controller method is called. It may:
o Interact with the Model to get data.
o Apply application logic.
4. Model Interaction
The Model communicates with the database and returns the required data to the
Controller.
5. Passing Data to View
The Controller sends the retrieved data to the View.
6. View Rendering
The View generates HTML output for the browser.
7. Response Sent to Browser
The final HTML is sent to the user’s browser for display.

[Link] Advantages of MVC in CodeIgniter

1. Separation of Concerns – Code is divided into clear sections (data, logic, presentation).
2. Reusability – Models and Views can be reused in multiple Controllers.
3. Maintainability – Changes in one layer do not heavily affect others.
4. Parallel Development – Designers can work on Views while developers work on
Controllers and Models.
5. Scalability – Easy to add new features or modify existing ones.

[Link] Example: Simple MVC in CodeIgniter 4

EDUCATOR: ASST PROF TWINKLE PANCHAL 11


CHAPTER 3 CODEIGNITER FRAMEWORK

Step 1 – Model (app/Models/[Link])

<?php
namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model


{
protected $table = 'students';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email', 'course'];

public function getStudents()


{
return $this->findAll();
}
}

Step 2 – Controller (app/Controllers/[Link])

<?php
namespace App\Controllers;

use App\Models\StudentModel;

class Student extends BaseController


{
public function index()
{
$model = new StudentModel();
$data['students'] = $model->getStudents();

return view('student_list', $data);


}
}

Step 3 – View (app/Views/student_list.php)

<!DOCTYPE html>
<html>
<head>
<title>Student List</title>

EDUCATOR: ASST PROF TWINKLE PANCHAL 12


CHAPTER 3 CODEIGNITER FRAMEWORK

</head>
<body>
<h1>Students</h1>
<table border="1">
<tr><th>ID</th><th>Name</th><th>Email</th><th>Course</th></tr>
<?php foreach($students as $student): ?>
<tr>
<td><?= $student['id'] ?></td>
<td><?= $student['name'] ?></td>
<td><?= $student['email'] ?></td>
<td><?= $student['course'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

Step 4 – Route (app/Config/[Link])

$routes->get('students', 'Student::index');

3.3.3 Creating Models, Views, and Controllers

In CodeIgniter, every application is built using the MVC architecture:

 Model → Works with data (database operations).


 View → Displays information to the user (HTML, CSS, minimal PHP).
 Controller → Connects the Model and View, handles the main logic.

When we create a new feature in CodeIgniter, we usually create all three parts so they work
together.

1. Creating a Model

Purpose:
The Model interacts with the database and contains functions for fetching, inserting, updating,
and deleting data.

Steps to Create a Model in CodeIgniter 4:

1. Go to the app/Models/ folder.


2. Create a new PHP file, e.g., [Link].
3. Add the following code:

EDUCATOR: ASST PROF TWINKLE PANCHAL 13


CHAPTER 3 CODEIGNITER FRAMEWORK

<?php
namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model


{
protected $table = 'students'; // Database table name
protected $primaryKey = 'id'; // Primary key
protected $allowedFields = ['name', 'email', 'course']; // Columns that can be inserted/updated

// Function to get all students


public function getStudents()
{
return $this->findAll();
}
}

2. Creating a View

Purpose:
The View shows the data to the user in a proper layout.
It contains HTML and can use PHP to display variables.

Steps to Create a View:

1. Go to the app/Views/ folder.


2. Create a new file, e.g., student_list.php.
3. Add the following code:

<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>List of Students</h1>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Email</th><th>Course</th>
</tr>
<?php foreach ($students as $student): ?>
<tr>
<td><?= $student['id'] ?></td>
<td><?= $student['name'] ?></td>

EDUCATOR: ASST PROF TWINKLE PANCHAL 14


CHAPTER 3 CODEIGNITER FRAMEWORK

<td><?= $student['email'] ?></td>


<td><?= $student['course'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

3. Creating a Controller

Purpose:
The Controller receives the request, gets data from the Model, and sends it to the View.

Steps to Create a Controller:

1. Go to the app/Controllers/ folder.


2. Create a new file, e.g., [Link].
3. Add the following code:

<?php
namespace App\Controllers;

use App\Models\StudentModel;

class Student extends BaseController


{
public function index()
{
$model = new StudentModel(); // Create model object
$data['students'] = $model->getStudents(); // Fetch data from model
return view('student_list', $data); // Pass data to view
}
}

4. Adding a Route

For the Controller to be accessible, we need to add a route.

Steps:

1. Open app/Config/[Link].
2. Add:

$routes->get('students', 'Student::index');

EDUCATOR: ASST PROF TWINKLE PANCHAL 15


CHAPTER 3 CODEIGNITER FRAMEWORK

Now, visiting

[Link]

will run the Controller, fetch data from the Model, and display it in the View.

5. MVC Flow Summary

1. User Request → URL points to Controller.


2. Controller → Calls Model for data.
3. Model → Fetches data from the database.
4. Controller → Sends data to View.
5. View → Displays data in browser.

3.3.4 URL Routing and Default Controller Setup

In CodeIgniter, routing is the process of mapping a URL to a specific controller and method.
Instead of directly linking to files, CodeIgniter uses a routing system to decide which code
should run when a particular URL is requested.

Routing gives developers flexibility:

 You can create clean and readable URLs.


 You can hide the real file names and paths.
 You can control what happens when a user visits your site.

1. URL Routing in CodeIgniter

When a user enters a URL like: [Link]

It is not directly opening a file. Instead:

1. The request goes to CodeIgniter’s [Link] inside the public/ folder.


2. The routing system checks the app/Config/[Link] file.
3. Based on the routing rules, CodeIgniter decides which Controller and Method to call.

2. The [Link] File

All routing rules are stored in:

app/Config/[Link]

This file contains commands to tell CodeIgniter which URL should call which Controller.

Example:

EDUCATOR: ASST PROF TWINKLE PANCHAL 16


CHAPTER 3 CODEIGNITER FRAMEWORK

$routes->get('about', 'Pages::about');

Here:

 URL /about will run the about() method in the Pages Controller.

3. Types of Routes

A) Static Route

Directly maps a URL to a Controller and Method.

$routes->get('contact', 'Pages::contact');

B) Dynamic Route

Passes parameters from the URL to the Controller.

$routes->get('product/(:num)', 'Product::view/$1');

Here:

 (:num) means a number parameter.


 $1 will be replaced by that number.

Example:
/product/15 → calls Product::view(15).

4. Default Controller Setup

When a user visits:

[Link]

CodeIgniter needs to know which page to show first.


This is controlled by the default controller.

In app/Config/[Link], find and edit:

$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');

Here:

 Home is the default controller.

EDUCATOR: ASST PROF TWINKLE PANCHAL 17


CHAPTER 3 CODEIGNITER FRAMEWORK

 index is the default method.

Example:

Home Controller

<?php
namespace App\Controllers;

class Home extends BaseController


{
public function index()
{
echo "Welcome to My Website!";
}
}

Then visiting the main URL will show:

Welcome to My Website!

5. Example – Custom Default Controller

If you want the Dashboard Controller to be the starting page:

1. Create app/Controllers/[Link]:

<?php
namespace App\Controllers;

class Dashboard extends BaseController


{
public function index()
{
echo "This is the Dashboard!";
}
}

2. In [Link], change:

$routes->setDefaultController('Dashboard');

Now visiting [Link] will open the Dashboard.

EDUCATOR: ASST PROF TWINKLE PANCHAL 18


CHAPTER 3 CODEIGNITER FRAMEWORK

Term Meaning Example


Static Route Fixed URL → Fixed method $routes->get('about', 'Pages::about');
Dynamic Route URL with variable $routes->get('user/(:num)',
'User::profile/$1');
Default Controller loaded when no URL $routes->setDefaultController('Home');
Controller is given

 Routing rules are defined in app/Config/[Link].


 Static routes handle fixed pages; dynamic routes accept parameters.
 The default controller decides the home page.
 Clean URLs improve SEO and user experience.

3.4 Core Features in CodeIgniter

3.4.1 Form Validation Using CI Validation Library

When creating a website or web application, we often need to collect information from users
using forms — for example, a registration form, login form, or contact form.

However, not all users enter correct or complete information.


Some may:

 Leave required fields blank


 Enter incorrect email formats
 Type too few or too many characters
 Enter invalid numbers or data

Form Validation is the process of checking the user’s input to make sure it meets certain rules
before it is saved or processed.

In CodeIgniter, this is made very easy using the Validation Library.

Why is Form Validation Important?

1. Data Accuracy – Prevents incorrect data from being stored in the database.
2. Security – Protects against harmful inputs like scripts (XSS attacks).
3. User Experience – Shows helpful error messages when the user makes a mistake.
4. Efficiency – Saves time by catching errors early.

CodeIgniter Validation Library Overview

CodeIgniter has a built-in Validation Library that:

EDUCATOR: ASST PROF TWINKLE PANCHAL 19


CHAPTER 3 CODEIGNITER FRAMEWORK

 Allows setting rules for each form field.


 Checks the input against those rules.
 Returns error messages if rules are broken.
 Works both server-side and can be combined with client-side validation.

The Validation Library is usually loaded automatically in CodeIgniter 4, so you can use it
directly inside your controller.

Steps for Form Validation in CodeIgniter 4

We will create a simple Registration Form with validation.

Step 1 – Create a Route

Open app/Config/[Link] and add:

$routes->get('register', 'User::register');
$routes->post('register', 'User::register');

This means:

 When the user visits /register, it will call the register() method in User controller.
 It works for both GET (show form) and POST (form submission).

Step 2 – Create the Controller

Go to app/Controllers/ and create [Link]:

<?php
namespace App\Controllers;

use CodeIgniter\Controller;

class User extends Controller


{
public function register()
{
helper(['form']); // Load form helper
$data = [];

if ($this->request->getMethod() == 'post') {

// Validation Rules
$rules = [
'username' => 'required|min_length[3]|max_length[20]',

EDUCATOR: ASST PROF TWINKLE PANCHAL 20


CHAPTER 3 CODEIGNITER FRAMEWORK

'email' => 'required|valid_email',


'password' => 'required|min_length[6]'
];

if ($this->validate($rules)) {
// If validation passes
$data['success'] = "Form submitted successfully!";
} else {
// If validation fails
$data['validation'] = $this->validator;
}
}

echo view('register_form', $data);


}
}

Step 3 – Create the View

Go to app/Views/ and create register_form.php:

<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Register</h2>

<?php if (isset($validation)): ?>


<div style="color:red;">
<?= $validation->listErrors() ?>
</div>
<?php endif; ?>

<?php if (isset($success)): ?>


<div style="color:green;">
<?= $success ?>
</div>
<?php endif; ?>

<form method="post" action="<?= base_url('register') ?>">


<label>Username</label>
<input type="text" name="username" value="<?= set_value('username') ?>"><br><br>

EDUCATOR: ASST PROF TWINKLE PANCHAL 21


CHAPTER 3 CODEIGNITER FRAMEWORK

<label>Email</label>
<input type="text" name="email" value="<?= set_value('email') ?>"><br><br>

<label>Password</label>
<input type="password" name="password"><br><br>

<button type="submit">Register</button>
</form>
</body>
</html>

Step 4 – How It Works

1. The user opens the form using GET /register.


2. They fill in the form and click Submit.
3. The data is sent via POST to the same controller method.
4. The Validation Library checks:
o Username: Required, between 3–20 characters.
o Email: Must be a valid email.
o Password: Required, at least 6 characters.
5. If any rule is broken, error messages are shown.
6. If all rules pass, a success message appears (and you can save the data in the database).

Common Validation Rules in CodeIgniter

Rule Description
required Field cannot be empty
min_length[n] Must have at least n characters
max_length[n] Must not exceed n characters
valid_email Must be a valid email address
numeric Must contain only numbers
matches[field] Must match another field (e.g., confirm password)
alpha Only letters
alpha_numeric Only letters and numbers

Advantages of Using CI Validation Library

1. Built-in – No need to write separate PHP validation functions.


2. Customizable – You can set your own rules and messages.
3. Error Handling – Easily display all errors or individual field errors.
4. Security – Prevents dangerous input before saving to the database.

EDUCATOR: ASST PROF TWINKLE PANCHAL 22


CHAPTER 3 CODEIGNITER FRAMEWORK

Example – Adding Custom Error Messages

$rules = [
'username' => [
'rules' => 'required|min_length[3]',
'errors' => [
'required' => 'Username is required.',
'min_length' => 'Username must have at least 3 characters.'
]
]
];

3.4.2 Session Management and Flashdata

In web applications, sessions are used to store and remember user information while they browse
through multiple pages.
HTTP (the protocol used by web browsers) is stateless, meaning it does not remember what
happened before.
If we want to keep track of the user’s login status, shopping cart items, or temporary settings, we
need Session Management.

CodeIgniter 4 provides a built-in Session Library to handle session data easily.


It also has a special feature called flashdata, which is used to store temporary messages that
last only for the next request.

1. Session Management

Definition:
Session Management is the process of storing data on the server (or browser) for a specific user,
so it can be accessed on multiple pages until the session ends.

Examples of Session Use:

 Storing logged-in user details


 Shopping cart items in e-commerce sites
 Temporary preferences (e.g., selected language)
 CSRF tokens for security

2. Sessions Work in CodeIgniter

1. The session is started automatically when you load the session service.
2. Session data is stored in a file (default), database, or browser cookie.
3. Each user gets a unique session ID.
4. Data stored in the session is available across different pages until:
o The user logs out

EDUCATOR: ASST PROF TWINKLE PANCHAL 23


CHAPTER 3 CODEIGNITER FRAMEWORK

o The session expires


o The session is manually destroyed

3. Loading the Session Library

In CodeIgniter 4, sessions can be used with:

$session = \Config\Services::session();

However, in most cases, CodeIgniter automatically loads it when needed.

4. Basic Session Operations

A) Storing Data in Session

$session = session();
$session->set('username', 'John');

B) Retrieving Data from Session

$username = $session->get('username');
echo $username; // Outputs: John

C) Storing Multiple Values

$session->set([
'username' => 'John',
'email' => 'john@[Link]'
]);

D) Removing Data

$session->remove('username');

E) Destroying the Session

$session->destroy();

5. Flashdata – Temporary Session Data

Definition:
Flashdata is session data that is only available for the next request and is automatically deleted
afterwards.

EDUCATOR: ASST PROF TWINKLE PANCHAL 24


CHAPTER 3 CODEIGNITER FRAMEWORK

Purpose:
Useful for showing temporary messages like:

 "Login Successful"
 "Your form has been submitted"
 "Item added to cart"

A) Setting Flashdata

$session = session();
$session->setFlashdata('success', 'Data saved successfully!');

B) Getting Flashdata

echo $session->getFlashdata('success');

Flashdata messages are usually displayed once (e.g., after a form submission) and then
disappear.

6. Example – Using Session and Flashdata in a Controller

Controller: app/Controllers/[Link]

<?php
namespace App\Controllers;

class User extends BaseController


{
public function login()
{
$session = session();

// Example login check


$username = $this->request->getPost('username');
$password = $this->request->getPost('password');

if ($username === 'admin' && $password === '12345') {


$session->set('username', $username);
$session->setFlashdata('success', 'Welcome, ' . $username . '!');
return redirect()->to('/dashboard');
} else {
$session->setFlashdata('error', 'Invalid login details!');
return redirect()->to('/login');
}
}

EDUCATOR: ASST PROF TWINKLE PANCHAL 25


CHAPTER 3 CODEIGNITER FRAMEWORK

public function dashboard()


{
$session = session();
echo $session->getFlashdata('success'); // Shows welcome message once
}
}

7. Session Configuration in CodeIgniter

Session settings are found in:

app/Config/[Link]

Important properties:

 $sessionDriver → Storage method (CodeIgniter\Session\Handlers\FileHandler,


DatabaseHandler, etc.)
 $sessionCookieName → Cookie name for session
 $sessionExpiration → Session lifetime (in seconds)
 $sessionSavePath → Storage location (folder or database table)

8. Advantages of Session Management in CodeIgniter

1. Built-in – No need to manually handle cookies.


2. Secure – Supports encryption and regeneration of session IDs.
3. Easy to Use – Simple functions for storing, retrieving, and removing data.
4. Flashdata – Perfect for one-time success/error messages.

Feature Purpose Example


set() Store session data $session->set('key', 'value')
get() Retrieve session data $session->get('key')
remove() Delete specific session data $session->remove('key')
destroy() End session completely $session->destroy()
setFlashdata() Store one-time data $session->setFlashdata('msg', 'Done!')
getFlashdata() Retrieve one-time data $session->getFlashdata('msg')

3.4.3 Handling File Uploads

In many web applications, we allow users to upload files such as profile pictures, documents, or
images.
File Uploading is the process of transferring a file from the user’s device to the server.

CodeIgniter 4 provides an Upload Class and file handling functions that make it easy to handle
file uploads securely.

EDUCATOR: ASST PROF TWINKLE PANCHAL 26


CHAPTER 3 CODEIGNITER FRAMEWORK

1. File Upload Process in CodeIgniter

When a user uploads a file:

1. The HTML form sends the file to the server using the POST method and
enctype="multipart/form-data".
2. The Controller in CodeIgniter retrieves the file.
3. The file is validated (size, type, etc.).
4. If validation passes, the file is moved to the desired folder.

2. HTML Form for File Upload

<!DOCTYPE html>
<html>
<head>
<title>Upload File</title>
</head>
<body>
<h2>Upload an Image</h2>
<form method="post" action="<?= base_url('upload') ?>" enctype="multipart/form-data">
<input type="file" name="userfile">
<button type="submit">Upload</button>
</form>
</body>
</html>

3. Controller for File Upload

<?php
namespace App\Controllers;

class UploadController extends BaseController


{
public function index()
{
return view('upload_form');
}

public function upload()


{
$file = $this->request->getFile('userfile');

if ($file->isValid() && !$file->hasMoved()) {


$file->move(WRITEPATH . 'uploads'); // Moves to writable/uploads
echo "File uploaded successfully!";

EDUCATOR: ASST PROF TWINKLE PANCHAL 27


CHAPTER 3 CODEIGNITER FRAMEWORK

} else {
echo "Error uploading file.";
}
}
}

4. File Validation in CodeIgniter

We can set rules for file uploads:

$validationRule = [
'userfile' => [
'label' => 'File',
'rules' => 'uploaded[userfile]'
. '|is_image[userfile]'
. '|mime_in[userfile,image/jpg,image/jpeg,image/png]'
. '|max_size[userfile,2048]', // 2MB
],
];

if (!$this->validate($validationRule)) {
print_r($this->validator->getErrors());
}

5. Common Upload Functions

Function Purpose
$file->getName() Get original filename
$file->getSize() Get file size
$file->getExtension() Get file extension
$file->move() Move uploaded file to destination
$file->isValid() Check if file is valid

 Always validate file type and size.


 Store uploaded files outside the public/ folder to prevent direct access.
 Rename files before saving to avoid overwriting.

3.4.4 Loading Helpers and Libraries

In CodeIgniter, Helpers and Libraries are pre-written collections of functions and classes that
make development easier.
Instead of writing common functionality from scratch, we can load and use them directly.

1. Helpers

EDUCATOR: ASST PROF TWINKLE PANCHAL 28


CHAPTER 3 CODEIGNITER FRAMEWORK

Definition:
A helper is a collection of standalone functions that perform specific tasks. They are not classes
and do not require creating objects.

Examples of Helpers:

 url helper – functions for creating links and URLs.


 form helper – functions for creating form elements.
 text helper – functions for working with strings.

Loading a Helper:

helper('url');

Using a Helper Function:

echo base_url('products');

2. Libraries

Definition:
Libraries are classes that provide powerful features like file uploads, sessions, email handling,
form validation, etc.

Loading a Library:

$session = \Config\Services::session();

Example – Loading Email Library:

$email = \Config\Services::email();
$email->setTo('example@[Link]');
$email->setSubject('Test Email');
$email->setMessage('Hello from CodeIgniter!');
$email->send();

EDUCATOR: ASST PROF TWINKLE PANCHAL 29


CHAPTER 3 CODEIGNITER FRAMEWORK

3. Autoloading Helpers and Libraries

If you need a helper or library in every page, you can autoload it.

Open app/Config/[Link]:

public $helpers = ['url', 'form'];

Now these helpers will load automatically for every request.

4. Difference between Helpers and Libraries

Feature Helpers Libraries


Type Collection of functions Classes
Object Creation Not needed Needed (using Services)
Examples url, form, text Email, Session, Upload
Usage Simple utility tasks Complex functionality

5. Advantages

 Saves development time.


 Code is reusable and consistent.
 Reduces errors by using tested functions.
 Improves readability.

The difference between helper and library in CodeIgniter.

Sr
No Helper Library

1 Helper is a collection of common Library is a class that has a set of functions


functions which we can use within that permits for creating an instance of that
Models, Views as well as in Controllers. class by $this->load->library() function.
Once we include the helper file, we can
get access to the functions.
2 It is not written in object-oriented format. It is written in an object-oriented format.
3 It can be called in the same manner you You must create an object of the class to
call PHP functions. call library functions by using the $this-
>library_name->method().
4 All built-in helper file names are suffixed All built-in library files do not have a
with a specific suffix.
word _helper (ex: email_helper.php).

Conclusion

EDUCATOR: ASST PROF TWINKLE PANCHAL 30


CHAPTER 3 CODEIGNITER FRAMEWORK

CodeIgniter is an open-source and MVC-based framework used for web application


development on PHP. This framework contains libraries, an easier interface with a logical
structure to access these libraries, helpers, plug-ins, and other resources as well. It is easy to use
compared to other PHP frameworks. Codeigniter is called a loosely based MVC framework
because it does not need to obey a strict MVC pattern during application creation. It is not
important to create a model, we can use only view and controllers for creating an application. In
addition, one can modify CodeIgniter to utilize HMVC(Hierarchical Model View Controller) as
well.

PRACTICAL EXAMPLE:

Example 1:
Create a simple CodeIgniter 4 application that demonstrates the Model–View–Controller
(MVC) architecture and URL routing.

Requirements:

1. Create a Model named MessageModel that returns the text "Hello from the Model!".
2. Create a Controller named Hello that loads the MessageModel, retrieves the message,
and sends it to a View.
3. Create a View named hello_view.php that displays the message on a webpage.
4. Configure URL routing in app/Config/[Link] so that:
o Visiting [Link] loads the Hello controller’s
index() method.
o The default controller is set to Hello so visiting
[Link] directly shows the message.
5. Add an extra route with a parameter (e.g., /greet/{name}) so that visiting
[Link] displays "Hello, sita".

Expected Output:

 Accessing / or /welcome should show:

ANSWER:

Step File Purpose


Create Controller app/Controllers/[Link] Handles request & loads view
Create View app/Views/hello_view.php Displays HTML output
Create Model app/Models/[Link] Handles data logic
Routing app/Config/[Link] Maps URLs to controllers
Default [Link] Loads controller when no URL is
Controller given

Step 1: Create the Controller

EDUCATOR: ASST PROF TWINKLE PANCHAL 31


CHAPTER 3 CODEIGNITER FRAMEWORK

Controllers are placed in the app/Controllers/ folder.

File: app/Controllers/[Link]

<?php
namespace App\Controllers;

class Hello extends BaseController


{
public function index()
{
// Load the view file
return view('hello_view');
}
}

Step 2: Create the View

Views are placed in the app/Views/ folder.

File: app/Views/hello_view.php

<!DOCTYPE html>
<html>
<head>
<title>Hello View</title>
</head>
<body>
<h1>Welcome to CodeIgniter 4!</h1>
<p>This message is from the View file.</p>
</body>
</html>

Step 3: Create the Model

Models are placed in the app/Models/ folder.


Let’s create a model that stores a message.

File: app/Models/[Link]

<?php
namespace App\Models;

use CodeIgniter\Model;

class MessageModel extends Model


{
public function getMessage()
{
return "Hello from the Model!";
}

EDUCATOR: ASST PROF TWINKLE PANCHAL 32


CHAPTER 3 CODEIGNITER FRAMEWORK

Step 4: Use the Model in the Controller

Update app/Controllers/[Link]:

<?php
namespace App\Controllers;
use App\Models\MessageModel;

class Hello extends BaseController


{
public function index()
{
$model = new MessageModel();
$data['message'] = $model->getMessage();

return view('hello_view', $data);


}
}

Step 5: Display the Message in the View

Update app/Views/hello_view.php:

<!DOCTYPE html>
<html>
<head>
<title>Hello View</title>
</head>
<body>
<h1><?= $message ?></h1>
</body>
</html>

2. URL Routing and Default Controller Setup


Step 1: Basic URL Routing

 All routing settings are in app/Config/[Link].


 To route /welcome to the Hello controller:

$routes->get('welcome', 'Hello::index');

Now visiting [Link] will load the Hello controller’s


index() method.

Step 2: Setting the Default Controller

EDUCATOR: ASST PROF TWINKLE PANCHAL 33


CHAPTER 3 CODEIGNITER FRAMEWORK

 The default controller loads when no controller is specified in the URL.


 In app/Config/[Link]:

$routes->setDefaultController('Hello');
$routes->setDefaultMethod('index');

Now visiting [Link] will directly open the Hello controller.

Step 3: Example Routing with Parameters


$routes->get('greet/(:any)', 'Hello::greet/$1');

And in [Link]:

public function greet($name)


{
echo "Hello, " . $name;
}

Visiting [Link] will display:

Hello, Sita

Example 2:
Create a simple CodeIgniter 4 application for Simple Form Validation.

Answer:

Step 1: Create Controller

File: app/Controllers/[Link]

<?php
namespace App\Controllers;

class FormTest extends BaseController


{
public function index()
{
helper(['form']); // Load form helper
echo view('form_view'); // Load the form
}

public function submitForm()


{
helper(['form']);
$validation = \Config\Services::validation();

EDUCATOR: ASST PROF TWINKLE PANCHAL 34


CHAPTER 3 CODEIGNITER FRAMEWORK

// Set validation rules


$rules = [
'name' => 'required|min_length[3]',
'email' => 'required|valid_email'
];

if ($this->validate($rules)) {
// If validation passes
echo "Form submitted successfully!";
} else {
// If validation fails, reload form with errors
echo view('form_view', [
'validation' => $this->validator
]);
}
}
}

Step 2: Create View

File: app/Views/form_view.php

<!DOCTYPE html>
<html>
<head>
<title>Form Validation Example</title>
</head>
<body>

<h2>Simple Form Validation</h2>

<!-- Display validation errors -->


<?php if (isset($validation)) : ?>
<?= $validation->listErrors() ?>
<?php endif; ?>

<form action="<?= base_url('form-submit') ?>" method="post">


<label>Name:</label>
<input type="text" name="name"><br><br>

<label>Email:</label>
<input type="text" name="email"><br><br>

<button type="submit">Submit</button>
</form>

</body>
</html>

Step 3: Set Routes

Open app/Config/[Link] and add:

EDUCATOR: ASST PROF TWINKLE PANCHAL 35


CHAPTER 3 CODEIGNITER FRAMEWORK

$routes->get('form-test', 'FormTest::index');
$routes->post('form-submit', 'FormTest::submitForm');

How It Works

1. User visits [Link] to see the form.


2. User enters Name and Email.
3. CI4’s Validation Library checks:
o Name is required and must be at least 3 characters.
o Email must be in valid email format.
4. If validation passes → shows "Form Submitted Successfully!".
5. If validation fails → reloads form with error messages.

Output Examples:

Case 1: Invalid Input

- The Name field must be at least 3 characters in length.


- The Email field must contain a valid email address.

Case 2: Valid Input

Form submitted successfully!

Example 3:
Write a CodeIgniter Application where:

 A session stores a username.


 Flashdata shows a "Login successful" message only once.

ANSWER:

Step 1: Create Controller

File: app/Controllers/[Link]

<?php
namespace App\Controllers;

class SessionTest extends BaseController


{
public function login()
{
// Start session
$session = session();

EDUCATOR: ASST PROF TWINKLE PANCHAL 36


CHAPTER 3 CODEIGNITER FRAMEWORK

// Store username in session


$session->set('username', 'Twinkle');

// Set flashdata message (shows only once)


$session->setFlashdata('success', 'Login successful!');

return redirect()->to('dashboard');
}

public function dashboard()


{
$session = session();

// Get username from session


$username = $session->get('username');

// Pass username and flashdata to view


return view('dashboard_view', [
'username' => $username,
'success' => $session->getFlashdata('success')
]);
}

public function logout()


{
$session = session();
$session->destroy(); // Remove all session data

echo "You have been logged out!";


}
}

Step 2: Create View

File: app/Views/dashboard_view.php

<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>

<?php if (!empty($success)) : ?>


<p style="color: green;"><?= $success ?></p>
<?php endif; ?>

<h2>Welcome, <?= $username ?></h2>


<p>This is your dashboard.</p>

<a href="<?= base_url('logout') ?>">Logout</a>

</body>

EDUCATOR: ASST PROF TWINKLE PANCHAL 37


CHAPTER 3 CODEIGNITER FRAMEWORK

</html>

Step 3: Set Routes

Open app/Config/[Link] and add:

$routes->get('login', 'SessionTest::login');
$routes->get('dashboard', 'SessionTest::dashboard');
$routes->get('logout', 'SessionTest::logout');

How It Works

1. Login Step:
o Visit [Link]
o CI4 starts a session, stores "RAM" as username, and sets flashdata "Login
successful!" .
o Redirects to dashboard.
2. Dashboard Step:
o Shows "Login successful!" message only once (flashdata disappears after one
request).
o Displays "Welcome, RAM".
3. Logout Step:
o Visit /logout → Session is destroyed, and username is removed.

Output Example:

First Visit to Dashboard after Login:

Login successful!
Welcome, RAM

Refreshing the Dashboard:

Welcome, RAM

(Flashdata disappears after first display)

Example 3:
Write a CodeIgniter Application for Handling file uploads

ANSWER:

Step 1: Create Controller

File: app/Controllers/[Link]

EDUCATOR: ASST PROF TWINKLE PANCHAL 38


CHAPTER 3 CODEIGNITER FRAMEWORK

<?php
namespace App\Controllers;

class UploadTest extends BaseController


{
public function index()
{
helper(['form']); // Load form helper
echo view('upload_form'); // Show the upload form
}

public function uploadFile()


{
helper(['form']);
$file = $this->request->getFile('userfile');

if ($file->isValid() && !$file->hasMoved()) {


// Move file to writable/uploads folder
$file->move(WRITEPATH . 'uploads');

echo "File uploaded successfully: " . $file->getName();


} else {
echo "File upload failed!";
}
}
}

Step 2: Create View

File: app/Views/upload_form.php

<!DOCTYPE html>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>

<h2>Upload a File</h2>

<form action="<?= base_url('upload-file') ?>" method="post"


enctype="multipart/form-data">
<label>Select file:</label>
<input type="file" name="userfile" required>
<br><br>
<button type="submit">Upload</button>
</form>

</body>
</html>

Step 3: Set Routes

EDUCATOR: ASST PROF TWINKLE PANCHAL 39


CHAPTER 3 CODEIGNITER FRAMEWORK

Open app/Config/[Link] and add:

$routes->get('upload-test', 'UploadTest::index');
$routes->post('upload-file', 'UploadTest::uploadFile')

Step 4: Create Upload Folder

 By default, CodeIgniter saves files in the writable/uploads folder.


 Make sure the folder exists:
o Go to writable/
o Create a folder named uploads
o Give it write permissions (e.g., chmod 777 uploads in Linux).

How It Works

1. Visit [Link] → Displays file upload form.


2. Choose a file and click Upload.
3. File is stored inside writable/uploads/ folder.
4. Success or failure message is shown.

Output Example:

File uploaded successfully: [Link]

EXAMPLE 4:
Create a simple CodeIgniter 4 application to demonstrate the use of Helpers and Libraries.

Requirements:

1. Load the Form Helper and create a form that accepts a user’s name.
2. Load the Email Library and send a test email with a subject and message to a given
email address.
3. Configure routes so that:
o Visiting /helper-test loads the form created using the helper.
o Visiting /send-email sends the test email and displays a success or failure
message.

Expected Output:

 Visiting /helper-test should display a form generated using Form Helper functions.
 Visiting /send-email should display either:

ANSWER:

EDUCATOR: ASST PROF TWINKLE PANCHAL 40


CHAPTER 3 CODEIGNITER FRAMEWORK

Step 1: Create Controller

File: app/Controllers/[Link]

<?php
namespace App\Controllers;

class HelperLibraryTest extends BaseController


{
public function index()
{
// Load a helper (form helper)
helper(['form']);

// Create a simple form using helper function


echo form_open('submit-form');
echo form_label('Enter Name: ', 'name');
echo form_input('name');
echo form_submit('submit', 'Submit');
echo form_close();
}

public function sendEmail()


{
// Load the Email library
$email = \Config\Services::email();

// Set email details (dummy example)


$email->setFrom('you@[Link]', 'Your Name');
$email->setTo('student@[Link]');
$email->setSubject('Test Email');
$email->setMessage('This is a test email using CI4 library.');

if ($email->send()) {
echo "Email sent successfully!";
} else {
echo "Email sending failed.";
}
}
}

Step 2: Set Routes

Open app/Config/[Link] and add:

$routes->get('helper-test', 'HelperLibraryTest::index');
$routes->get('send-email', 'HelperLibraryTest::sendEmail');

Step 3: How It Works

1. Visit [Link]
o The Form Helper is loaded and used to create a form.

EDUCATOR: ASST PROF TWINKLE PANCHAL 41


CHAPTER 3 CODEIGNITER FRAMEWORK

2. Visit [Link]
o The Email Library is loaded and used to send a test email.

Key Points

 Helpers are small functions that help with common tasks (e.g., form_helper,
url_helper, text_helper).
 Libraries are classes that provide bigger functionality (e.g., email, session,
pagination).
 Helpers are loaded with:
 helper(['form', 'url']);
 Libraries are loaded with:
 $email = \Config\Services::email();

EDUCATOR: ASST PROF TWINKLE PANCHAL 42

You might also like