0% found this document useful (0 votes)
3 views31 pages

PHP Unit 1

The document provides a comprehensive overview of web development using PHP and MySQL, covering PHP basics, arrays, string manipulation, functions, object-oriented programming, error handling, and MySQL database operations. It also introduces the Laravel PHP framework and highlights PHP's features such as open-source nature, server-side scripting, and extensive library support. Additionally, it includes practical examples and guidelines for creating dynamic web applications with PHP.

Uploaded by

chakrapanimca12
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)
3 views31 pages

PHP Unit 1

The document provides a comprehensive overview of web development using PHP and MySQL, covering PHP basics, arrays, string manipulation, functions, object-oriented programming, error handling, and MySQL database operations. It also introduces the Laravel PHP framework and highlights PHP's features such as open-source nature, server-side scripting, and extensive library support. Additionally, it includes practical examples and guidelines for creating dynamic web applications with PHP.

Uploaded by

chakrapanimca12
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
You are on page 1/ 31

WEB DEVELOPMENT USING PHP & MYSQL

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.

Some important points need to be noticed about PHP are as followed:

➢ PHP stands for Hypertext Preprocessor.


➢ PHP is an interpreted language, i.e., there is no need for compilation.
➢ PHP is faster than other scripting languages, for example, ASP and JSP.
➢ PHP is a server-side scripting language, which is used to manage the dynamic content of the
website.
➢ PHP can be embedded into HTML.
➢ PHP is an object-oriented language.
➢ PHP is an open-source scripting language.
➢ PHP is simple and easy to learn language.
Features of PHP
Open Source: PHP is an open-source language, which means anyone can use it freely without paying
for a license. You can download its source code, study it, and even modify it to suit your project
needs. This makes PHP a cost-effective choice for students and developers.
Server-Side Scripting: PHP runs on the server, not in the user's browser. When someone visits a
webpage that uses PHP, the code is processed on the server, and the result (usually HTML) is sent
to the browser. This makes PHP suitable for tasks like login systems, data handling, and file
processing.
Platform Independent: PHP works across different operating systems such as Windows, Linux,
and macOS. It also supports major web servers like Apache and Nginx. This means you can run PHP
scripts on almost any setup without needing to change your code.
Easy to Learn and Use: PHP has a simple and clean syntax, making it easy for beginners to learn.
If you're familiar with C, Java, or JavaScript, you'll find PHP very readable. Even complex tasks can
often be completed in just a few lines of PHP code.
Fast Execution: PHP is known for its fast execution time, especially when compared to other server-
side scripting languages. It is lightweight and performs well, which helps in building responsive and
fast-loading web applications.

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.

Object-Oriented Programming (OOP): PHP supports object-oriented programming, allowing


developers to create classes, objects, and reusable code. OOP makes PHP suitable for large and
complex applications where organization and reusability are important.

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

Step 2: Add PHP to System PATH


1. Search "Edit the system environment variables" → Open.
2. Click Environment Variables → In "System variables", find Path → Click Edit.
3. Click New, then paste:
C:\php
4. Click OK → OK → OK.
5. Now open Command Prompt and type:
php -v
➢ You should see PHP version info (e.g., PHP 8.2.x)

Create a PHP file:

Example: Create a file test.php with this content:

<?php
echo "Hello from PHP!";
?>

Save it in a folder, e.g., C:\projects\php-site\test.php

Open Command Prompt or Terminal:

Navigate to the folder:

Ex > cd C:\projects\php-site

Run PHP Server in (cmd):


php -S localhost:8000

Open Browser:
6
Visit: http://localhost:8000/test.php

You will see:


Hello from PHP!

3. Adding Dynamic Content


• Concept:
o Using PHP to generate content that changes based on variables, functions,
conditions, loops, or external data (like: current time, user input, database queries).

• 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:

If the time is 09:00 AM:

Good morning, John!

If the time is 03:00 PM:

Good afternoon, John!

If the time is 08:00 PM:

Good evening, John!

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>";

echo $GLOBALS['globalVar'] . "<br>"; // Another way to access global


$localVar = "I am local";
echo $localVar . "<br>";
}
testScope();
// echo $localVar; // This would cause an error
o Static Scope: Used within functions. A static variable retains its value between
function calls.
PHP
function counter() {
static $count = 0; // Initialized only once
$count++;
echo $count . "<br>";
}
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
• Variable-Variables: Allows you to use the value of a variable as the name of another
variable.
PHP
$foo = "bar";
$$foo = "baz"; // This creates a variable named $bar with value "baz"
echo $foo; // Output: bar
echo $$foo; // Output: baz

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).

• Naming Convention: Typically defined in uppercase letters, often with underscores


separating words.

• Accessing: Do not use $ prefix when accessing constants.


o Example: echo PI;

• Scope: Constants are global by default.


• Example program:
<?php
define("PI", 3.14159);
echo PI;
?>
Output: 3.14159

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.

Why are operators important in PHP?


Operators are the building blocks of any PHP script. Without them, your program
couldn't perform calculations, make decisions, manipulate data, or interact
dynamically with information. They allow you to:

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.

➢ Arithmetic Operators: Perform mathematical calculations.


Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulus. These operators work on
numeric values and return numeric results.
o + (Addition),
o - (Subtraction),
o * (Multiplication),
o / (Division),
o % (Modulo - remainder),
o ** (Exponentiation - PHP 5.6+)
Example:
<?php
$a = 10;
$b = 3;
// Addition
echo $a + $b;
echo "<br>"; // Output: 13
// Subtraction
echo $a - $b;
echo "<br>"; // Output: 7
// Multiplication
echo $a * $b;
11
echo "<br>"; // Output: 30
// Division
echo $a / $b;
echo "<br>"; // Output: 3.333...
// Modulus (Remainder)
echo $a % $b;
echo "<br>”; // Output: 1
?>

➢ Assignment Operators: Assign values to variables.


Assignment operators in PHP are used to assign values to variables. The most
common assignment operator is the equals sign (=), but PHP provides compound
assignment operators that combine other operations (like addition or multiplication) with
assignment.
o = (Assignment),
o += (Add and assign),
o -= (Subtract and assign),
o *= (Multiply and assign),
o /= (Divide and assign),
o %= (Modulo and assign), **= (Exponentiate and assign)

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>";
?>

➢ Comparison Operators: Compare two values; return true or false.


Comparison operators are used to compare two values or expressions. The result
of a comparison is a Boolean value: either TRUE or FALSE. These operators are most
commonly used in conditional statements like if, while, for, etc.

o == (Equal - value only)


o === (Identical - value and data type)
o != or <> (Not equal - value only)
o !== (Not identical - value or data type)
o < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or
equal to)
o <=> (Spaceship operator - PHP 7+, returns -1, 0, or 1 for less than, equal, greater
than respectively)
Example Program:
<?php
$a = 10;
$b = 20;

echo ($a == $b) ? "Equal<br>" : "Not Equal<br>"; // Not Equal

echo ($a != $b) ? "Not Equal<br>" : "Equal<br>"; // Not Equal

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

echo ($a === $b) ? "Identical<br>" : "Not Identical<br>"; // Not Identical

?>

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.

o && or and (Logical AND) - true if both operands are true.


o || or or (Logical OR) - true if at least one operand is true.
o ! (Logical NOT) - Inverts the boolean value.
o xor (Logical XOR) - true if one operand is true but not both.

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.

o ++$var (Pre-increment: increments, then returns value)


o $var++ (Post-increment: returns value, then increments)
o --$var (Pre-decrement: decrements, then returns value)
o $var-- (Post-decrement: returns value, then decrements)
➢ String Operator:
o . (Concatenation): Joins two strings. Example: "Hello" . " World" results in
"Hello World".
➢ Error Control Operator:
o @: Suppresses error messages for the expression it precedes. (Generally
discouraged in production as it hides potential issues, better to use proper error
handling).

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.';

➢ integer: Whole numbers (positive, negative, or zero).


PHP
$age = 30;
$quantity = -10;
15
➢ float (or double): Floating-point numbers (numbers with a decimal point or in
exponential form).
PHP
$price = 19.99;
$pi = 3.14159;

➢ boolean: Represents truth values: true or false. Case-insensitive.


A Boolean is a data type that can hold only two possible values:

• 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;

var_dump($bool1); // Output: bool(true)


var_dump($bool2); // Output: bool(false)
?>

Compound Types (hold multiple values):


➢ array: An ordered map. Can hold elements of different data types. Can be indexed
numerically or associatively (using strings as keys).
PHP
$colors = ["Red", "Green", "Blue"]; // Indexed array
$person = ["name" => "Bob", "age" => 25]; // Associative array

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";
}

9. Accessing Form Variables


• Purpose: To retrieve data submitted by a user through HTML forms.
• Superglobals: PHP provides special predefined arrays called "superglobals" that are
always accessible from anywhere in the script.

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).

o $_REQUEST: An associative array that by default contains the contents of


$_GET, $_POST, and $_COOKIE.
▪ Caution: Using $_REQUEST can be less precise as it might contain data
from various sources; it's generally better to explicitly use $_GET or
$_POST for clarity and security.

• Example (HTML Form):


HTML
<form action="process.php" method="post">
Name: <input type="text" name="userName"><br>
Email: <input type="email" name="userEmail"><br>
<input type="submit" value="Submit">
</form>

• Example (PHP Processing process.php):


PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['userName']; // Accessing input field named 'userName'
$email = $_POST['userEmail']; // Accessing input field named 'userEmail'

echo "Hello, " . htmlspecialchars($name) . "!<br>";


echo "Your email is: " . htmlspecialchars($email);
} else {
echo "Form not submitted via POST method.";

18
}
?>

10. Variable Handling Functions


• isset($var): Checks if a variable is set (declared and not null). Returns true or false.
o Example: if (isset($_POST['userName'])) { ... }

• empty($var): Checks if a variable is empty. Returns true if the variable is considered


empty ("", 0, 0.0, "0", NULL, FALSE, an empty array, or a variable declared but not
assigned).
o Example: if (empty($name)) { echo "Name cannot be empty."; }

• unset($var): Destroys a variable, freeing its memory. The variable becomes


undefined.
o Example: unset($tempVar);

• gettype($var): Returns the type of a variable (e.g., "string", "integer", "array",


"boolean", "null", "object", "resource", "unknown type").
o Example: echo gettype($age); // Output: integer

• 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)

• var_dump($var, ...): Displays structured information about one or more expressions,


including its type and value. Useful for debugging.
o Example: var_dump($person);

• print_r($var, $return = false): Prints human-readable information about a


variable. If $return is true, it returns the output as a string instead of printing it. Useful
for arrays and objects.
o Example: print_r($colors);

11. Making Decisions with Conditions


• Purpose: To execute different blocks of code based on whether a specified condition is
true or false.
• if...else if...else Statement:

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.

2. Opening a File (fopen())


• Function: fopen(string $filename, string $mode, bool $use_include_path = false,
resource $context = null)
• Returns: A file pointer resource on success, false on failure.
• $filename: The path to the file.
• $mode: Specifies the type of access you require to the file. This is crucial.
o Read Modes:
▪ 'r': Read only. File pointer at the beginning. Error if file doesn't exist.
▪ 'r+': Read and write. File pointer at the beginning. Error if file doesn't
exist.
o Write Modes (caution: can overwrite data!):
▪ 'w': Write only. File pointer at the beginning. Truncates (empties) file if it
exists. Creates file if it doesn't exist.
▪ 'w+': Read and write. File pointer at the beginning. Truncates file if it
exists. Creates file if it doesn't exist.
o Append Modes:
▪ 'a': Write only. File pointer at the end of the file. Creates file if it doesn't
exist. Existing content is preserved.
▪ 'a+': Read and write. File pointer at the end of the file. Creates file if it
doesn't exist. Existing content is preserved.

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.");
}

3. Writing to a File (fwrite() / fputs())


• Function: fwrite(resource $handle, string $string, int $length = null)
• Returns: The number of bytes written, or false on error.
• $handle: The file pointer obtained from fopen().
• $string: The string to write to the file.
• $length (Optional): Maximum number of bytes to write. If omitted, the entire string is
written.
• Alias: fputs() is an alias for fwrite().
• Example:
PHP
$file = fopen("data.txt", "w"); // Opens in write mode, truncates if exists
if ($file) {
$text = "Hello, PHP file handling!\n";
fwrite($file, $text);
fwrite($file, "This is another line.");

26
fclose($file);
echo "Data written to data.txt";
} else {
echo "Error opening file.";
}

4. Closing a File (fclose())


• Function: fclose(resource $handle)
• Returns: true on success, false on failure.
• Importance:
o Resource Release: Frees up the file handle, making it available for other
operations.
o Data Flush: Ensures that any buffered data is written from memory to the
physical file.
o Prevents Corruption: Leaving files open can lead to data corruption, especially if
the script terminates unexpectedly.
• Example: (See fwrite() example above)

5. Reading from a File


• fread(resource $handle, int $length):
o Reads $length bytes from the file.
o Returns the read string, or false on error.
o Use filesize() to read the entire file.
o Example:
PHP
$file = fopen("data.txt", "r");
if ($file) {
$content = fread($file, filesize("data.txt")); // Reads entire file
echo "File Content: <pre>" . htmlspecialchars($content) . "</pre>";
fclose($file);
} else {
echo "Error opening file.";
}
• fgets(resource $handle, int $length = null):

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>";
}
}

6. Other File Functions


• file_exists(string $filename): Checks whether a file or directory exists. Returns true or
false.
o Example: if (file_exists("config.ini")) { /* ... */ }
• is_file(string $filename): Checks if a given filename is a regular file.
• is_dir(string $filename): Checks if a given filename is a directory.
• filesize(string $filename): Returns the size of the file in bytes, or false on error.
• unlink(string $filename): Deletes a file. Returns true on success, false on failure.
o Example: if (unlink("old_data.txt")) { echo "File deleted."; }
• rename(string $oldname, string $newname, resource $context = null): Renames a file or
directory. Can also be used to move a file between directories on the same filesystem.
o Example: rename("temp.txt", "final.txt");
• copy(string $source, string $dest, resource $context = null): Copies a file. Returns true
on success, false on failure.
o Example: copy("template.html", "new_page.html");
• Directory Functions:
o mkdir(string $pathname, int $mode = 0777, bool $recursive = false, resource
$context = null): Creates a directory. $mode specifies permissions (e.g., 0777 for
full permissions). $recursive=true allows creating nested directories.
o rmdir(string $dirname, resource $context = null): Removes an empty directory.
o opendir(string $path, resource $context = null): Opens a directory handle.
o readdir(resource $dir_handle): Reads an entry from an open directory handle.
o closedir(resource $dir_handle): Closes an open directory handle.

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.

7. Locking Files (flock())


• Purpose: To prevent multiple processes (or multiple requests to the same PHP script)
from simultaneously writing to the same file, which can lead to data corruption (race
conditions). This is an advisory lock, meaning other programs must also respect the lock
for it to be effective.
• Function: flock(resource $handle, int $operation, int &$wouldblock = null)
• Returns: true on success, false on failure.
• $handle: The file pointer obtained from fopen().
• $operation: Specifies the type of lock.
o LOCK_SH: Acquire a shared lock (readers lock). Multiple processes can hold
shared locks simultaneously.
o LOCK_EX: Acquire an exclusive lock (writer lock). Only one process can hold
an exclusive lock at a time.
o LOCK_UN: Release a lock.
o LOCK_NB: Non-blocking lock. If the lock cannot be acquired immediately,
flock() returns false instead of waiting.
• Example (Exclusive Write Lock):
PHP
$file = fopen("log.txt", "a"); // Open for appending
if ($file) {
if (flock($file, LOCK_EX)) { // Acquire an exclusive lock
fwrite($file, "Log entry at " . date("Y-m-d H:i:s") . "\n");
flock($file, LOCK_UN); // Release the lock
echo "Log entry added successfully.";
} else {
echo "Could not get lock on file.";
}
fclose($file);
} else {
echo "Error opening log file.";
}

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.

End of Unit-I Notes

31

You might also like