PHP Unit 1
PHP Unit 1
Unit-I: Using PHP: PHP Basics: Accessing PHP, Creating Sample Application, Embedding PHP in
HTML, Adding Dynamic Content, Identifiers, Variables, Constants, Operators, Data types, Accessing
Form Variables, Variable handling Functions, Making Decisions with Conditions, Repeating actions
through Iterations, Breaking Out of a Control Structure Storing and Retrieving Data: Processing Files,
opening a File, writing to a File, closing a F ile, Reading from a File, Other File Functions, Locking
Files.
Unit-II: Arrays: Arrays basics, Types, Operators, Array Manipulations. String Manipulation and
Regular Expressions: Strings Basics, Formatting Strings, Joining and Splitting Strings with String
Functions, Comparing Strings, Matching and Replacing Substrings with String Function, Introducing
Regular Expressions, Find, Replace, Splitting in Regular Expressions
Unit-III: Reusing Code and Writing Functions: advantages of Reusing, Using require () and include
(), Using Functions in PHP, Scope, Passing by Reference Versus Passing by Value, keyword,
Recursion. Object-Oriented PHP: OOP Concepts, Creating Classes, Attributes, and Operations in PHP,
Implementing Inheritance in PHP, Understanding Advanced Object-Oriented Functionality in PHP.
Error and Exception Handling: Error and Exception Handling, Exception Handling Concepts.
Unit-IV: Using MySQL: Relational Database Concepts, Web Database Architecture, Introducing
MySQL’s Privilege System, Creating Database Tables, Understanding MySQL, Identifiers, Database
Operations, querying a Database, Understanding the Privilege System, Making Your MySQL
Database Secure, Optimization, Backup, Restore.
Unit-V: Introduction of Laravel PHP Framework: Why Laravel, setting up Laravel Development
Environment, Routing and Controllers: introduction to MVC, the HTTP verbs, and REST, Route
Definitions, Route Groups, Signed Routes, Views, Controllers, Route Model Binding, Redirects,
Custom Responses
1
What is PHP:- PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used to develop
web applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. The current stable
version of PHP is PHP 8.4, with the latest point release 8.4.10, officially released on July 3, 2025.
2
Database Support: PHP can connect to almost any database, such as MySQL, PostgreSQL, SQLite,
Oracle, and MongoDB. This allows developers to store and retrieve data easily. PHP has built-in
functions and libraries to manage database operations smoothly.
Extensive Library and Framework Support: PHP has a wide range of built-in libraries and
supports many powerful frameworks like Laravel, Symfony, and CodeIgniter. These tools help speed
up development and encourage clean, structured code.
Security Features: PHP provides many features to help write secure code, such as input validation,
data sanitization, password hashing, and prepared statements to prevent SQL injection attacks. While
security also depends on the developer, PHP provides all the tools needed to build safe applications.
Large Community and Documentation: PHP has a huge global community, which means it's easy
to find help, tutorials, forums, and shared code. The official PHP documentation is also extensive
and beginner-friendly, making it easier for students to learn and find solutions.
Dynamic Content Creation: PHP can be used to create dynamic content on web pages. For
example, it can display different messages based on user input, pull data from a database, or manage
forms. This makes it very useful for creating interactive websites.
3
PHP Basics:
Accessing PHP
• Definition: PHP (Hypertext Preprocessor) is a widely-used open-source general-purpose
scripting language that is especially suited for web development and can be embedded
into HTML.
• Server-Side Scripting: PHP code is executed on the server, not the client's browser. The
server processes the PHP script, generates plain HTML (or other content), and sends
that HTML to the browser.
• Execution Flow:
1. User requests a .php file from the web server (e.g., index.php).
2. The web server (e.g., Apache, Nginx) identifies the .php extension and passes the
request to the PHP interpreter.
3. The PHP interpreter executes the PHP code, interacts with databases, files, etc.,
as instructed.
4. The PHP interpreter sends the generated HTML (or other output) back to the
web server.
5. The web server sends this final HTML to the user's browser.
• Local Development Environment: To run PHP locally, you need a web server, PHP
interpreter, and often a database (like MySQL). Popular bundles include:
o XAMPP: (Apache + MySQL + PHP + Perl) for Windows, macOS, Linux.
o WAMP: (Windows Apache MySQL PHP) for Windows.
o MAMP: (macOS Apache MySQL PHP) for macOS.
• Syntax Delimiters: PHP code is enclosed within special tags:
o Standard: <?php ... ?> (Recommended)
o Short open tag: <? ... ?> (Requires short_open_tag to be enabled in php.ini,
generally discouraged for portability).
o Script tag: <script language="php"> ... </script> (Less common).
o ASP style tags: <% ... %> (Requires asp_tags to be enabled, generally
discouraged).
4
2. Creating Sample Application & Embedding PHP in HTML
• Purpose: To demonstrate how PHP can be mixed with HTML to produce dynamic
content.
• Basic Structure:
HTML
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<h1>Welcome!</h1>
<?php
// PHP code goes here
echo "<p>This content is generated by PHP.</p>";
$name = "Student";
echo "<p>Hello, " . $name . "!</p>";
?>
<p>This is static HTML content.</p>
</body>
</html>
• Key Points:
o PHP code blocks can be placed anywhere within an HTML document.
o The echo statement is used to output content to the browser.
o The PHP interpreter only processes code within <?php ... ?> tags; everything
else is treated as plain HTML.
5
Step-by-step: How to Run Your PHP File:
Step 1: Install PHP
For Windows:
1. Go to: https://windows.php.net/download/
2. Download "Thread Safe" Zip file under your PHP version (e.g., PHP 8.x.x).
3. Extract it to a folder, for example:
Eg: C:\php
4. Rename php.ini-development to php.ini
<?php
echo "Hello from PHP!";
?>
Ex > cd C:\projects\php-site
Open Browser:
6
Visit: http://localhost:8000/test.php
• Examples:
o Current Date/Time: echo "Today is: " . date("Y-m-d H:i:s");
o Personalized Greeting: Based on a user's name or login status.
o Conditional Display: Showing different content based on whether a user is logged in.
o Looping Data: Displaying a list of items fetched from an array or database.
Example Program:
<?php
$name = "John";
$hour = date("H");
if ($hour < 12) {
echo "Good morning, $name!";
} elseif ($hour < 18) {
echo "Good afternoon, $name!";
} else {
echo "Good evening, $name!";
}
?>
Explanation:
• $name is a variable holding the user’s name.
• date("H") gets the current hour (24-hour format).
• Based on the time of day, it shows a different greeting.
7
Sample Output:
4. Identifiers
• Definition: Names given to variables, functions, classes, constants, etc.
• Rules:
o Must start with a letter (a-z, A-Z) or an underscore (_).
o Can contain letters, numbers (0-9), and underscores.
o Case-sensitive: myVar is different from myvar. (This is crucial for variables,
functions, etc., but class names are often treated case-insensitively in some
contexts for convenience, though best practice is to match the declared case).
o Cannot contain spaces or special characters (except _).
o Keywords (e.g., if, else, while, echo) cannot be used as identifiers.
5. Variables
• Definition: A named storage location that holds data. In PHP, variables are loosely
typed, meaning you don't declare their data type explicitly.
• Syntax: All variables in PHP start with a dollar sign ($).
o Example: $name = "John Doe";
• Assignment: Values are assigned using the assignment operator (=).
• Variable Scope:
o Local Scope: Variables declared inside a function are local to that function and
cannot be accessed from outside.
o Global Scope: Variables declared outside any function have global scope. They
can be accessed from anywhere outside functions. To access a global variable
inside a function, you must use the global keyword or the $GLOBALS
superglobal array.
8
PHP
$globalVar = "I am global"; // Global variable
function testScope() {
// echo $globalVar; // This would cause an error (undefined variable)
global $globalVar; // Access global variable
echo $globalVar . "<br>";
9
echo $bar; // Output: baz
(Use with caution, can make code hard to read and debug).
6. Constants
• Definition: Identifiers for simple values that cannot be changed during the execution
of the script.
• Declaration:
o define() function: define("PI", 3.14159); (Older, for runtime definition, often for
global constants).
o const keyword: const GRAVITY = 9.8; (Since PHP 5.3, preferred for class-level
constants or compile-time constants).
7. Operators
An operator in PHP is a special symbol or keyword that performs an operation on one
or more values or variables. These values are called operands.
10
1. Manipulate Data: Perform arithmetic, string concatenation, array operations.
2. Control Flow: Make decisions using comparisons and logical operators within if,
else, switch statements.
3. Assign Values: Store and update data in variables.
4. Interact with Structures: Access properties and methods of objects or elements of
arrays.
Analogy: Imagine you have a calculator. The numbers you type in are the operands, and the
buttons you press (like +, -, x, /) are the operators. Pressing an operator tells the calculator
what to do with the numbers.
Example Program:
<?php
$a = 10;
$b = 5;
$a += $b; // $a = $a + $b = 15
echo "After += : $a <br>";
$a -= $b; // $a = $a - $b = 10
echo "After -= : $a <br>";
$a *= $b; // $a = $a * $b = 50
echo "After *= : $a <br>";
$a /= $b; // $a = $a / $b = 10
echo "After /= : $a <br>";
12
$a %= $b; // $a = $a % $b = 0
echo "After %= : $a <br>";
?>
echo ($a < $b) ? "a is less<br>" : "a is not less<br>"; // a is less
echo ($a > $b) ? "a is greater<br>" : "a is not greater<br>"; // a is not greater
?>
13
➢ Logical Operators: Combine conditional statements.
Logical operators are used to combine two or more conditions and return a
Boolean value (true or false) based on logical relationships. They are most commonly
used in conditional statements like if, while, and loops.
Example Program:
<?php
$a = 10;
$b = 5;
if ($a == 10 && $b == 5) {
echo "Both conditions are true<br>"; // Output
}
if ($a == 10 || $b == 3) {
echo "At least one condition is true<br>"; // Output
}
if (!($a == $b)) {
echo "a is not equal to b<br>"; // Output
}
?>
14
➢ Increment/Decrement Operators: Increase or decrease a variable's value by
one.
Increment and Decrement operators are used to increase or decrease a variable's value
by 1. These are unary operators, meaning they operate on a single operand (variable). They
are commonly used in loops, counters, and numeric logic operations.
8. Data Types
• Definition: Classification of data that tells the PHP interpreter how the data is intended
to be used. PHP is a loosely typed language, meaning variables do not need explicit type
declarations.
• Scalar Types (hold a single value):
o string: Sequence of characters. Enclosed in single (') or double (") quotes.
Double quotes allow for variable parsing ("Hello, $name") and escape sequences
(\n, \t).
PHP
$name = "Alice";
$greeting = "Hello, $name!"; // "Hello, Alice!"
$message = 'It\'s a beautiful day.';
• TRUE (1)
• FALSE (0)
Booleans are used in conditional statements to control the flow of the program, such
as if, else, while, etc.
true or TRUE
false or FALSE
PHP
<?php
$bool1 = true;
$bool2 = false;
16
➢ object: Instances of classes. Represents a specific entity with properties (data) and
methods (functions).
PHP
class Car {
public $model = "Sedan";
}
$myCar = new Car();
Special Types:
➢ resource: A special variable, holding a reference to an external resource
(e.g.,database connection, file handle, image).
PHP
$fileHandle = fopen("data.txt", "r"); // $fileHandle is a resource
➢ null: A variable that has no value. It is the only possible value of the null type.
PHP
$x = null;
if (is_null($x)) { // true
echo "x is null";
}
o $_GET: An associative array of variables passed to the current script via the
URL parameters (GET method).
▪ Use Case: Retrieving data from query strings (e.g.,
example.com/page.php?id=123&name=test).
▪ Characteristics: Data is visible in the URL, limited in size, suitable for non-
sensitive data or for bookmarking.
17
o $_POST: An associative array of variables passed to the current script via the
HTTP POST method.
▪ Use Case: Retrieving data from HTML forms submitted with
method="post".
▪ Characteristics: Data is not visible in the URL, no practical size limits,
suitable for sensitive data (passwords) or large amounts of data (file
uploads).
▪
18
}
?>
• settype($var, $type): Sets the type of a variable. Returns true on success, false on
failure.
o Example: $num = "123"; settype($num, "integer"); // $num becomes 123
(integer)
19
o Executes a block of code if a condition is true, and optionally another block if the
first condition is false, or other blocks if subsequent conditions are true.
o Syntax:
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition1 is false AND condition2 is true
} else {
// Code to execute if all preceding conditions are false
}
Example:
PHP
$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
• switch Statement:
o Used to perform different actions based on different conditions for a single
variable. Often more readable than long if-else if chains when checking against
many specific values.
o Syntax:
switch (expression) {
case value1:
// Code to execute if expression == value1
break; // Important: exits the switch block
case value2:
case value3: // Multiple cases can share a block
20
// Code to execute if expression == value2 OR expression == value3
break;
default:
// Code to execute if no case matches (optional)
}
Example:
PHP
$dayOfWeek = "Tuesday";
switch ($dayOfWeek) {
case "Monday":
echo "Start of the week.";
break;
case "Tuesday":
case "Wednesday":
echo "Midweek blues.";
break;
case "Friday":
echo "TGIF!";
break;
default:
echo "Weekend or unknown day.";
}
• Ternary Operator (Conditional Operator):
o A shorthand for simple if-else statements, useful for conditional assignments.
o Syntax: condition ? value_if_true : value_if_false;
o Example:
PHP
$age = 18;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status; // Output: Adult
21
12. Repeating actions through Iterations (Loops)
• Purpose: To execute a block of code repeatedly until a certain condition is met.
• for loop:
o Used when you know (or can calculate) how many times the loop should run.
o Syntax: for (initialization; condition; increment/decrement) { // code to execute }
o Example:
PHP
for ($i = 1; $i <= 5; $i++) {
echo "Count: " . $i . "<br>";
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
• while loop:
o Used when the number of iterations is unknown, and the loop continues as long
as a specified condition is true. The condition is checked before each iteration.
o Syntax: while (condition) { // code to execute }
o Example:
PHP
$j = 1;
while ($j <= 3) {
echo "Number: " . $j . "<br>";
$j++;
}
// Output:
// Number: 1
// Number: 2
// Number: 3
22
• do-while loop:
o Similar to while, but guarantees that the code block is executed at least once,
because the condition is checked after the first iteration.
o Syntax: do { // code to execute } while (condition);
o Example:
PHP
$k = 5;
do {
echo "Do-While Number: " . $k . "<br>";
$k++;
} while ($k <= 3); // Condition is false, but runs once
// Output: Do-While Number: 5
• foreach loop:
o Specifically designed for iterating over elements of arrays and objects. It
simplifies array traversal.
o Syntax (for values): foreach ($array as $value) { // code to execute }
o Syntax (for keys and values): foreach ($array as $key => $value) { // code to
execute }
o Example:
PHP
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
$student = ["name" => "Raju", "roll" => "101", "class" => "XII"];
foreach ($student as $key => $val) {
echo $key . ": " . $val . "<br>";
}
23
13. Breaking Out of a Control Structure
• break Statement:
o Used to terminate the execution of the current for, foreach, while, do-while, or
switch structure. Execution resumes at the statement immediately following the
terminated structure.
o Example (Loop):
PHP
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i is 5
}
echo $i . "<br>";
}
// Output: 1, 2, 3, 4
o Example (Switch): (Already seen in switch section, crucial for preventing "fall-
through")
• continue Statement:
o Used to skip the rest of the current iteration of the loop (for, foreach, while, do-
while) and proceed to the next iteration.
o Example:
PHP
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip the rest of this iteration when $i is 3
}
echo $i . "<br>";
}
// Output: 1, 2, 4, 5
24
Storing and Retrieving Data:
Processing Files
1. Processing Files (Introduction)
• Purpose: PHP provides functions to interact with the server's file system, allowing you
to create, read, write, append, delete, and manage files and directories.
• File Paths:
o Absolute Path: Full path from the root directory (e.g., /var/www/html/data.txt on
Linux, C:\xampp\htdocs\data.txt on Windows).
o Relative Path: Path relative to the current script's directory (e.g., data.txt if in
the same directory, ../config/settings.txt).
• Permissions: File system operations depend on the web server's (and PHP process's)
permissions on the files/directories. If PHP doesn't have write access, file write
operations will fail.
25
o Exclusive Creation Modes (for safe creation):
▪ 'x': Write only. Creates the file. Returns false if file already exists. Useful
for preventing accidental overwrites.
▪ 'x+': Read and write. Creates the file. Returns false if file already exists.
o Write/Create (No Truncate) Mode:
▪ 'c': Write only. If the file does not exist, it is created. If it exists, it is not
truncated. The file pointer is at the beginning.
▪ 'c+': Read and write. If the file does not exist, it is created. If it exists, it is
not truncated. The file pointer is at the beginning.
• Error Handling: Always check if fopen() returns false to handle cases where the file
cannot be opened (e.g., wrong path, permission issues).
PHP
$file = fopen("myfile.txt", "w") or die("Unable to open file!");
// Or more robustly:
$file = fopen("myfile.txt", "w");
if ($file === false) {
die("Error: Could not open file for writing.");
}
26
fclose($file);
echo "Data written to data.txt";
} else {
echo "Error opening file.";
}
27
o Reads a single line from the file. Reading stops when $length - 1 bytes have been
read, or on a newline, or at EOF.
o Returns the read string, or false on error/EOF.
o Example (Reading line by line):
PHP
$file = fopen("data.txt", "r");
if ($file) {
echo "Reading line by line:<br>";
while (!feof($file)) { // Loop until end of file
echo fgets($file) . "<br>";
}
fclose($file);
}
• fgetc(resource $handle):
o Reads a single character from the file.
o Returns the character, or false on error/EOF.
• file_get_contents(string $filename, bool $use_include_path = false, resource $context =
null, int $offset = 0, int $maxlen = null):
o Reads an entire file into a string. Simpler for small files.
o Returns: The file content string, or false on failure.
o Example:
PHP
$content = file_get_contents("data.txt");
if ($content !== false) {
echo "Content (via file_get_contents): " . htmlspecialchars($content);
} else {
echo "Error reading file.";
}
• file(string $filename, int $flags = 0, resource $context = null):
o Reads an entire file into an array. Each element of the array corresponds to a
line in the file.
o $flags: Can include FILE_SKIP_EMPTY_LINES,
FILE_IGNORE_NEW_LINES.
28
Example:
PHP
$lines = file("data.txt", FILE_IGNORE_NEW_LINES); // Each line as an array element
if ($lines !== false) {
echo "Lines from file:<br>";
foreach ($lines as $lineNum => $line) {
echo ($lineNum + 1) . ": " . htmlspecialchars($line) . "<br>";
}
}
29
o scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING,
resource $context = null): Returns an array of files and directories from the
specified directory. Easier than opendir/readdir for simple listings.
30
• Key points for flock():
o Locks are released automatically when the file is closed or the script ends.
o It's crucial to release locks (LOCK_UN) when done to allow other processes to
acquire them.
o It's a system-level advisory lock, not a mandatory lock.
31