Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
213 views24 pages

Bca (5sem) - Web Development Using PHP & Mysql

The document outlines a B.C.A. (Honours) course on Web Development using PHP and MySQL, covering topics such as PHP basics, arrays, functions, object-oriented programming, and MySQL database management. It includes practical case studies for web-based applications, e-commerce solutions, and CMS development. Additionally, it introduces the Laravel PHP framework and emphasizes the importance of dynamic content in web applications.
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)
213 views24 pages

Bca (5sem) - Web Development Using PHP & Mysql

The document outlines a B.C.A. (Honours) course on Web Development using PHP and MySQL, covering topics such as PHP basics, arrays, functions, object-oriented programming, and MySQL database management. It includes practical case studies for web-based applications, e-commerce solutions, and CMS development. Additionally, it introduces the Laravel PHP framework and emphasizes the importance of dynamic content in web applications.
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/ 24

B.C.A.

(HONOURS) Computer Applications (Major)


SEMESTER-V
COURSE 13: 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 File, Reading from a File, Other
File Functions, Locking Files. CASE STUDY: Web Based Social Network Application
Development

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 CASE STUDY:
Retail E-commerce Application Development for Apparels & Garments

Unit-III
Reusing Code and Writing Functions: The 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. CASE STUDY: e-Commerce Application for Manufacturing Industry

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. CASE STUDY: Custom CMS Website
Development

Unit-V
Introduction of Laravel PHP Framework: Why Lavarel, setting up Lavarel 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 Case Study: E-commerce Business Solution delivered for Groceries Vendor

1
UNIT-I
Using PHP
Q . Embedding PHP in HTML
HTML is a pre-defined front end language code, whereas php is a server-side scripting language;
it is also called an embedded server-side language. Most of the PHP syntax codes has to be
followed with the c, java and Perl script languages. It normally works with other web-based
dynamic script languages, and also performance side, it will be more better compared to other
script languages whereas it is paired with html codes for creating web-based applications it is a
non-interruptible functioning type for creating the websites.
Syntax:
<html>
<head>
<script language="php">
-----some codes----
</script>
</head>
</html>
To use Embed PHP in HTML
 In Php code, we also wrote an embedded code inside. It normally looks like an HTML
code it also runs in the normal browsers as the source the raw PHP code is not visible in
the browsers because the interpreter in the PHP has run through the script mode, and also it
will display the output as from the expected script results as the user is given inputs and
getting outputs as test cases.
 This means that the PHP code, which we will already reproduce with the clean html
viewable codes with any type of web browsers, instead the user does not understand the
PHP codes in the browsers.
 This type of process will come in the server-side scripting concepts in a nutshell thats why
PHP has an interpreted and executed within the web browsers compatible with any type of
user’s local PCs.
 Generally, PHP codes have a basic type of syntax like html as the first type of document.
PHP tag will be used in the html code; in the below PHP tag, we will write the logic using
PHP syntax and statements and finally, it will have the whitespace for comment purposes.
The view part will be shown like normal html codes because PHP codes are written in
script tags.
Ex :
<html>
<title>First Application of PHP</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
echo "Welcome User";
?>
</body>
</html>
Importance of Embed PHP in HTML
 PHP is also used as a command-line code script written in desktop applications or
standalone applications but mainly focuses on web-based applications. Normally the client
user sends the request to the server; the request itself has the PHP code is happened, the

2
response will be in either xml or json type it will become from the server. PHP is used for
creating dynamic web sites.
 We probably know that PHP can create dynamic websites, and PHP is quite easy to learn
when compared to other server-side languages. PHP is open-source, and its components
are free for usages and also easily available in the open-source market. Hence opensource,
we will use PHP. The free syntax is very easy to use. PHP runs all type of Operating
Systems like Windows, MacoX, Linux and Sun Solaris etc. it is one of the main benefits of
PHP.
 PHP supports all type of web servers like Apache Tomcat, IIS Servers, Jetty etc. This
facility will be more comfortable for PHP application developers to develop a flexible
environment that will save more time. Compared to other application programming
languages, PHP will be deployed more easily, and hosting companies for the PHP will be
more the server of the hosted companies for running the PHP applications will be less
costly.
 The Market of PHP Applications are taken as less effort when compared to other high
complexity applications. It is one of the best features of the PHP language. In the Olden
Days, the market of web applications will take more time to reaching the market; it takes
fewer chances of getting more popular in the market, and competition also used to be more
on that time. Performance-wise will be more reliable with the user, so it is an effective
language for user perspectives.
 PHP is also the same as compared to other languages like java; they have their own
predefined functions and libraries. It has the feature like sending emails, connect with other
network services it will generate jpeg, gif images etc., and also it generates pdf, excels
documents for downloading the web page contents in the applications.
 PHP applications are more user-friendly because it is easy to understand and it is
simplicity one.
 It is also one of the ways to secure web applications and websites; it has a security layer to
protect against threats, malwares etc when compared to other languages, it has more
secured. It has an Extension feature for user support, and it is easy to integrate.

Q . Adding Dynamic Content


Adding dynamic content means including information that changes based on specific
conditions or user data, rather than displaying static, unchanging text or images. This
allows for personalization and more engaging user experiences.
Here's a breakdown of how to add dynamic content, along with key concepts:
1. Understanding Dynamic Content:
 Personalization: Dynamic content tailors information to individual users based on their
data (e.g., name, location, preferences).
 Contextual Updates: Content can change based on the user's actions, time, or other
factors.
 Real-time Updates: Some dynamic content, like stock prices or news headlines, updates
in real-time.
 Conditional Logic: Content is displayed based on specific rules or conditions.
2. How to Add Dynamic Content:
 Content Management Systems (CMS):

3
Many CMS platforms (like WordPress, Wix, etc.) have built-in features or plugins to
manage dynamic content.
 Email Marketing Platforms:
Tools like Acoustic, Oracle Eloqua, and Dotdigital allow you to add dynamic content to
email campaigns.
 Web Development:
Dynamic content can be added to websites using programming languages like JavaScript,
along with APIs and databases.
 Expression Editors:
Platforms like Power Automate use expression editors to incorporate dynamic content
into workflows.
3. Examples of Dynamic Content:
 Personalized greetings: Displaying "Hello, [User's Name]" in an email.
 Location-based offers: Showing nearby store locations or tailored product
recommendations.
 Data-driven recommendations: Suggesting products based on purchase history.
 Real-time stock quotes: Displaying the latest stock prices on a financial website.
 Personalized email subject lines: Including the recipient's name or other relevant
information.
 Conditional content in emails: Showing different content blocks based on user segments.
4. Tips for Using Dynamic Content:
 Know your audience:
Understand your users' needs and preferences to create relevant dynamic content.
 Use tools strategically:
Leverage marketing tools and platforms that simplify the dynamic content process.
 Ensure responsiveness:
If adding dynamic content to emails, verify that it displays correctly across different
devices.
 Test your dynamic content:
Preview your dynamic content with various user data to ensure it works as expected.
 Comply with privacy regulations:
Be transparent about how you collect and use user data for personalization.

Q . Identifiers
In PHP, identifiers are names given by programmers to program elements like variables,
functions, classes, constants, and more. They act as labels or handles that allow programmers to
refer to and manipulate these elements within their code.
Purpose: Identifiers help programmers organize and manage different parts of their code by
providing unique names to various elements.

4
Rules:
 Identifiers can be of any length.
 They can include letters (both uppercase and lowercase), numbers, and
underscores.
 The first character of an identifier must be a letter or an underscore.
 Identifiers are generally case-sensitive, meaning myVariable and MyVariable are
treated as different identifiers.
 Keywords (reserved words like if, else, while) cannot be used as identifiers.

Examples:
 $name (a variable)
 calculate_sum (a function)
 MyClass (a class)
 MY_CONSTANT (a constant)

Case Sensitivity:
PHP is case-sensitive for identifiers, meaning uppercase and lowercase letters are treated
differently. For example, $userName and $username would be distinct variables.
Built-in Functions:
There's an exception to the case sensitivity rule for some built-in functions, like print,
which can be called as Print.
Function/Variable Name Conflicts:
A variable can have the same name as a function, but it's generally best to avoid this
practice to prevent confusion.

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

To Declare a Variable in PHP


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

Syntax : $variable_name = value;


Ex :
$name = "John";
// A number (integer)
$age = 25;
// A decimal number (float)
$price = 12.50;
Variable Rules :
 A variable must start with a $ symbol, then its name.
 The variable name must start with a letter or underscore (_).
 A variable name cannot start with a number.

5
 The variable name can contain letters, digits or underscores.
 PHP is case sensitive, so $Name and $name are distinct variables.

Variable Types in PHP


 String : A sequence of characters.
 Integer : A whole number (without decimals).
 Float (Double) : A decimal number.
 Boolean : Represents true or false values.
 Array : Stores multiple values in one variable.
 NULL : Represents a variable with no value.

Q . Constants
A constant in PHP is a name or an identifier for a simple value. A constant value cannot change
during the execution of the PHP script. It basically improves code readability and maintainability.
Constants make it easier to manage the configuration settings.
They make code easier to read and prevent key values from changing. Constants can be used
anywhere in the application. PHP also contains built-in constants such as PHP_VERSION.
Constants help make the code simple and secure.

Rules of Constants in PHP


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

Syntax : define("CONSTANT_NAME", value);

Create a PHP Constant :


Creating a PHP constant is straightforward. You use the `define()` function, which takes two
mandatory parameters & one optional parameter:
1. Name of the constant: This is the identifier you’ll use to refer to the constant. By convention,
constant names are written in uppercase letters to distinguish them from variables.
2. Value of the constant: This is the fixed value assigned to the constant.
3. Case-insensitivity (optional): By default, constants are case-sensitive. If you want to make
them case-insensitive, you can set this parameter to `true`.
Ex :

<?php
// Step 1: Define the constant
define("WELCOME_MESSAGE", "Hello, welcome to our website!");
// Step 2: Use the constant
echo WELCOME_MESSAGE;
?>

6
Q . Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators
are used to perform operations on variables or values. For example: $num=10+20;
 Arithmetic Operators
 Logical or Relational Operators
 Comparison Operators
 Conditional or Ternary Operators
 Assignment Operators
 Increment/Decrement Operators
 String Operators
PHP Arithmetic Operators :
The arithmetic operators are used to perform common arithmetical operations, such as addition,
subtraction, multiplication etc. Here's a complete list of PHP's arithmetic operators:

Operator Description Example

+ Addition $x + $y
- Subtraction $x - $y
* Multiplication $x * $y
/ Division $x / $y
% Modulus $x % $y
Ex:
<?php
$x = 10; $y = 4;
echo($x + $y);
?>

0utputs: 14

Assignment Operators :
The assignment operators are used to assign values to variables.
Operator Description Example

= Assign $x = $y
+= Add and assign $x += $y
-= Subtract and assign $x -= $y
*= Multiply and assign $x *= $y
/= Divide and assign quotient $x /= $y
%= Divide and assign modulus $x %= $y

7
Comparison Operators : The comparison operators are used to compare two values in a Boolean
fashion.

Operator Name Example

== Equal $x == $y
!= Not equal $x != $y
< Less than $x < $y
> Greater than $x > $y
>= Greater than or equal to $x >= $y
<= Less than or equal to $x <= $y

Incrementing and Decrementing Operators


The increment/decrement operators are used to increment/decrement a variable's value.

Operator Name Effect

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

Conditional or Ternary Operators:


These operators are used to compare two values and take either of the results simultaneously,
depending on whether the outcome is TRUE or FALSE.
Syntax: $var = (condition)? value1 : value2;
Ex :
<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>
Output: The number is negative

Logical Operators : The logical operators are typically used to combine conditional statements.

Operator Example

and $x and $y
or $x or $y
&& $x && $y

8
|| $x || $y
! !$x
String Operators :
The string operators are used to perform the operation on strings. There are two string operators in
PHP, which are given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign


Assignment the concatenated string to $a, e.g. $a = $a
. $b

Q . DATA TYPES

 Scalar types : A variable is a scalar when it holds a single value of the type integer,
float, string, or boolean.
 Compound types : Compound data includes the values that contain more than one value.

1. Integer: Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point. They can be decimal (base 10), octal (base
8), or hexadecimal (base 16).
Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
Ex :

9
<?php
$x = 5985;
echo $x;
?>
2. Float :
float Can hold numbers containing fractional or decimal parts including positive and
negative numbers , which are also known as floats, doubles, or real numbers.
Ex :
<?php
$val = 50.85;
echo $val;
?
3. String
A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“).It
holds letters or any alphabets, numbers, and even special characters.
Ex :

<?php
$var = "welcome";
echo $var;
echo "Hello goodmorning";
?
4. Boolean: Boolean data types are used in conditional testing. Hold only two values,
either TRUE(1) or FALSE(0). Successful events will return true and unsuccessful events
return false.
Ex :
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
5. Array: Array is a compound data type that can store multiple values of the same data
type. An array is formally defined as an indexed collection of data values. Each index (also
known as the key) of an array is unique value.
Ex :
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
?>
6. Objects: Objects are defined as instances of user-defined classes that can hold both
values and functions and information for data processing specific to the class. Objects
are created based on template via the new keyword.
Ex :
<?php
class greeting{
function show_greeting ( ) {

10
$str = "Hello World";
echo $str;
}
}
$obj = new greeting ( );
$obj -> show_greeting ( );
?>
Output : Hello World
7. Resources: Resources in PHP are not an exact data type. These are basically used to store
references to some function call or to external PHP resources. For example, consider a
database call. This is an external resource. Resource variables hold special handles for
files and database connections.
8. Null :
Null is a special data type that has only one value: NULL. There is a convention of writing
it in capital letters as it is case sensitive. The special type of data type NULL defined a
variable with no value.
Ex :
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>

Q . Accessing Form Variables


PHP's form is validate data collected from the user, before processing. HTML forms are used to
allow users to enter their input to the application. The form element can contain multiple fields
like input box, select box, text area, checkbox, radio button and more.

Using these fields, the user can enter the data and submit to the server-side PHP file. The PHP file
name to be called on the submit event will be specified by using the for action attribute.

The form field values are added to the PHP global array based on the request type specified in the
form by using the method attribute. If the form method is GET then the form fields values are
stored into the $_GET array.

If it is POST, then the values are posted with the $_POST array. In the PHP file, the $_GET or
$_POST request array is used to access and process the user input submitted via the form.

Creating a Simple Contact Form


<html>
<head> <title>Contact Form</title> </head>
<body>
<h2>Contact Us</h2>
<form action="process-form.php" method="post">
Name: <input type="text" name="name" >
Email: <input type="text" name="email">
Subject: <input type="text" name="subject" >
Message:<textarea name="message" rows="5" cols="30"></textarea>

11
<input type="submit" value="Submit">
</form>
</body>
</html>
Output :

Explanation of code
Notice that there are two attributes within the opening <form> tag:
 The action attribute references a PHP file "process-form.php" that receives the data entered into
the form when user submit it by pressing the submit button.
 The method attribute tells the browser to send the form data through POST method.

Capturing Form Data with PHP


To access the value of a particular form field, you can use the following superglobal variables.
These variables are available in all scopes throughout a script.

Superglobal Description
$_GET Contains a list of all the field names and values sent by a form using
the get method (i.e. via the URL parameters).

$_POST Contains a list of all the field names and values sent by a form using
the post method (data will not visible in the URL).

$_REQUEST Contains the values of both the $_GET and $_POST variables as well
as the values of the $_COOKIE superglobal variable.

When a user submit the above contact form through clicking the submit button, the form data is
sent to the "process-form.php" file on the server for processing. It simply captures the information
submitted by the user and displays it to browser.

The PHP code of "process-form.php" file


<html>
<body> <h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_POST["name"]?></li>
<li><em>Email:</em> <?php echo $_POST["email"]?></li>
<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
<li><em>Message:</em> <?php echo $_POST["message"]?></li>
</ol>
</body>
</html>

12
Output :

Q . Variable Handling Functions


PHP Variable Handling Functions :
PHP supports the concept of variable functions. This means that if a variable name has parentheses
appended to it.
1) boolval( ) : The PHP Variable Handling boolval() function is used to get the boolean value of a
variable. So it returns a boolean value either true or false.
Syntax : bool boolval( mixed $value )
2) empty( ) : The PHP Variable Handling empty() function is used to check that a variable is empty
or not. A variable is considered empty if it is either nonexistent or has a value of false. The
empty() function does not generate a warning if there is no variable.
Syntax : bool empty ( mixed $var )
Ex :
<?php
$str = "";
if (empty($str)) {
echo "The string is empty.";
} else {
echo "The string is not empty.";
}
?>
3) Floatval( ) : The PHP Variable Handling floatval() function is used to to get the float value of a
variable. A float is a number with a decimal point, as 3.14 or 10.5. For example, if you enter
"10.5" as a string, 10.5 is returned as a float.
Syntax : float floatval ( mixed $value )
Ex :
<?php
$var = '56.138mln';
$float_value = floatval($var);
echo "Float value of the given number is: ".$float_value;
?>
4) get_resource_id() :The PHP Variable Handling get_resource_id() function is used to get a
resource's integer ID. In PHP, resources are specific data types such as database connections
and file handles. This function returns the unique ID linked to a resource.
Syntax : int get_resource_id ( resource $resource )
5) get_resource_type( ) : The PHP Variable Handling get_resource_type() function is used to
find the type of a given resource. In PHP, a resource is a variable that means external data, like
a database connection or an open file.

13
Ex :
<?php
$file = fopen("/PHP/PhpProjects/myfile.txt", "r");
echo "Resource type: " . get_resource_type($file) . PHP_EOL;
fclose($file);
?>
6) gettype( ) : The PHP Variable Handling gettype() function is used to PHP's gettype()
function is useful to identify the type of a variable. It returns the type as a string, such
"integer" or "string". For example, it can check to see if a variable contains a number, text, or
an array.
Syntax : string gettype ( mixed $value )
7) intval( ) : The PHP Variable Handling intval() function is used to convert a value to an
integer (a whole number).
Ex :
<?php
$num = 12.98;
$result = intval($num);
echo $result;
?>
Output : 12
8) is_array( ) : The PHP Variable Handling is_array() function is used to check whether a variable
is in an array. An array is a collection of data stored in a single variable. When you call this
function, it checks whether the variable you given is an array or not.
Syntax : bool is_array ( mixed $value )
9) is_int( ) : The PHP Variable Handling is_int() function is used to check if a variable is an
integer.
Syntax : bool is_int ( mixed $value )
Ex :
<?php
$value = 10;
if (is_int($value)) {
echo "The value is an integer.";
} else {
echo "The value is not an integer.";
}
?>
10) is_null( ) : The PHP Variable Handling is_null() function is used to checks whether a variable is
null. It returns true when the variable is null. It returns false if the variable contains any value.
Syntax : bool is_null ( mixed $value )
Ex :
<?php
$var = null;
if (is_null($var)) {
echo "Variable is null";
} else {
echo "Variable is not null";
}
?>

14
1) simple if
In simple if, controller initially checks the condition, if the condition is true it executes the true block
statements otherwise it skips the true block statements and executes the statements after the true block
statements.
Syntax: if( condition1, condition 2, … ) {
Statement1; // True Block Statement 2;

}

Ex :
<?php
$age = 50;
if ($age > 30){
echo "Your age is greater than 30!";
}
?>
2) if else statement:
if else is also called decision making statement. This statement has a simple condition with two
different blocks one is true block and other is false block.

In this statement first the condition will be checked. If the condition is true, then true block statements
will be executed otherwise false block (else block) statements will be executed.

Syntax: if( condition1, condition 2, … ) {


True Block Statements
}
else {
False Block Statements
}

15
Ex :
<?php
$age = 50;

if ($age < 30)


{
echo "Your age is less than 30!";
}
else
{
echo "Your age is greater than or equal to 30!";
}
?>

3) Else If Statement :
We can consider the elseif statement as an extension to the if-else construct. If you've got more
than two choices to choose from, you can use the elseif statement.
Syntax :
if (expression1)
{
// code is executed if the expression1 evaluates to TRUE
}
elseif (expression2)
{
// code is executed if the expression2 evaluates to TRUE
}
elseif (expression3)
{
// code is executed if the expression3 evaluates to TRUE
}
else
{
// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a
default choice
}
Ex :
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
elseif ($age > 30 && $age < 40)
{
echo "Your age is between 30 and 40!";
}
elseif ($age > 40 && $age < 50)
{

16
echo "Your age is between 40 and 50!";
}
else
{
echo "Your age is greater than 50!";
}
?>

Q . Repeating actions through Iterations


Loops are used to execute the same block of code again and again, as long as a certain condition is
met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the
time and effort. PHP supports four different types of loops.
 while
 do…while
 for
 foreach
while Loop
 The while statement will loops through a block of code as long as the condition specified
in the while statement evaluate to true.

Syntax :
while(condition){
// Code to be executed
}
Ex :
<?php
$i = 0;
while ($i < 5){
echo $i + 1 . "<br>";
$i++;
}
?> Output: 1 2 3 4 5

Do…while Loop :

17
The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop
iteration. With a do-while loop the block of code executed once, and then the condition is
evaluated, if the condition is true, the statement is repeated as long as the specified condition
evaluated to is true.

Syntax :
do{
// Code to be executed
}while(condition);
Ex :
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
} while($i <= 3);
?>

Output: 1 2 3

for loop :
The for statement is used when you know how many times you want to execute a statement or a
block of statements.
Syntax :
for (initialization; condition; increment/decrement)
{
code to be executed;
}
Parameters:
 initialization: Initialize the loop counter value
 condition : Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
 increment: Increases the loop counter value
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
} ?>

18
Output: 1 2 3

foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element
is assigned and the next counter is shifted to the next element.
Syntax:
foreach (array_element as value) {
//code to be executed
}
Ex :
<?php
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $val) {
echo "$val \n";
}
?>
Output: 10 20 30

Q . Breaking Out of a Control Structure


The break statement
 The PHP break keyword is used to terminate the execution of a loop prematurely.
 PHP break statement breaks the execution of the current for, while, do-while, switch and for-
each loop. If you use break inside the inner loop, it breaks the execution of the inner loop only

The break statement is situated inside the statement block. It gives you full control and whenever
you want to exit from the loop you can come out. After coming out of a loop immediate statement
to the loop will be executed.
Syntax :
jump statement;
break;
 Using break with while and do-while Loops
These loops run until a condition becomes false. You can stop them early with break.
Ex : while:

19
$i = 1;
while ($i <= 10) {
if ($i == 4) {
break;
}
echo $i;
$i++;
}

Ex : do-while :
$i = 1;
do {
if ($i == 3) {
break;
}
echo $i;
$i++;
} while ($i <= 5);

 Using break with for Loops :


A for loop repeats a block of code a set number of times. You can use break to stop it before
reaching the end.
Ex:
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i ;
}
Output:
1
2
3
4
 Using break with switch :
break is essential in switch statements to prevent falling through to other cases.
Ex:
$day = 'Tue';
switch ($day) {
case 'Mon': echo "Monday";
break;
case 'Tue': echo "Tuesday";
break;
case 'Wed': echo "Wednesday";
break;
default: echo "Other day";
}

20
Output: Tuesday

Q . Processing Files (File Handling)


Processing files in PHP involves a set of functions and techniques for interacting with the file
system. File handling in PHP refers to working with files, such as creating files, reading files,
writing files, and manipulating the files within the PHP. Functions like fopen(), fread() and
fwrite() are very useful.

1 . Opening a File :
 You can open a file with the fopen() function.
 It takes two arguments: the filename and the mode in which you want to open the file
(read, write, append, etc.).
Ex : $file = fopen("example.txt", "r");
 example.txt is the name of the file we want to open.
 "r" indicates that we are opening the file in read-only mode.

Reading Files with PHP:


Reading files is a fundamental operation when working with file handling in PHP. PHP provides
several functions to read data from files, depending on the specific requirements.
2.1 Using fopen( ) Function:
The fopen() function is the starting point for reading files. It takes two parameters – the file name
(along with the path) and the mode in which to open the file. Let’s see how to use fopen() to read
files:
Ex : $filename = 'example.txt';
$file = fopen($filename, 'r');
2.2 Reading Line-by-Line:
The above example reads the entire file, but sometimes you may want to read the file line-by-line
to process each line separately. The fgets() function allows you to read one line at a time:
Ex :
<?php
$filename = 'data.csv';
$file = fopen($filename, 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
// Process the line (e.g., parse CSV data)
}
fclose($file);
} else {
echo "Unable to open file.";
}
?>
2.3 Reading Entire File at Once:
If you need to read the entire file content into a single variable, you can use the file_get_contents()
function:
Ex :
<?php
$filename = 'example.txt';

21
$fileContent = file_get_contents($filename);
if ($fileContent !== false) {
// Process the entire file content
} else {
echo "Unable to read file.";
}
?>
3. Writing to Files with PHP:
Writing to files is crucial for storing data and updating files on the server. PHP provides methods
to create new files and append data to existing ones.
3.1 Creating New Files:
To create a new file and write data into it, use the “w” mode while opening the file with fopen():
Ex :
<?php
$filename = 'new_file.txt';
$file = fopen($filename, 'w');
if ($file) {
$data = "This is the content to be written in the new file.";
fwrite($file, $data);
fclose($file);
echo "File created and data written successfully.";
} else {
echo "Unable to create file.";
}
?>
3.2 Writing Data Line-by-Line:
To write data line-by-line to a file, use the file_put_contents() function with the “FILE_APPEND”
flag:
Ex :
<?php
$filename = 'data.txt';
$dataArray = array("Line 1", "Line 2", "Line 3");
foreach ($dataArray as $line) {
file_put_contents($filename, $line . PHP_EOL, FILE_APPEND);
?>
3.3 Appending Data to Existing Files:
If you want to add data to an existing file without overwriting its content, use the “a” mode:
Ex :
<?php
$filename = 'existing_file.txt';
$file = fopen($filename, 'a');
if ($file) {
$data = "This data will be appended to the existing file.";
fwrite($file, $data);
fclose($file);
echo "Data appended successfully.";
} else {
echo "Unable to open file.";

22
}
?>
PHP Close File :
When you are finished reading or writing to a file, use the fclose() method to properly close it.
This helps free up system resources.
Ex :
<?php
$file = fopen("/PHP/PhpProjects/myfile.txt", "r");
// Do something with the file
// Close the file
fclose($file);
echo "The file has been closed.";
?>

Q . Other File Functions


Apart from reading and writing, PHP offers various file manipulation functions to perform tasks
like copying, renaming, and deleting files.
4.1 Copying Files: The copy() function allows you to duplicate a file with a new name and
location:
Ex :
$sourceFile = 'source.txt';
$destinationFile = 'destination.txt';
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully.";
} else {
echo "Unable to copy file.";
}
4.2 Renaming Files: To rename a file, use the rename() function:
Ex :
$oldName = 'old_file.txt';
$newName = 'new_file.txt';
if (rename($oldName, $newName)) {
echo "File renamed successfully.";
} else {
echo "Unable to rename file.";
}
4.3 Deleting Files: The unlink() function is used to delete files:
Ex :
$filename = 'file_to_delete.txt';
if (unlink($filename)) {
echo "File deleted successfully.";
} else {
echo "Unable to delete file.";
}
Q . Locking Files.

23
File locking in PHP is primarily achieved using the flock() function. The PHP Filesystem flock(
) function is used to lock or release a file. This function allows us to perform a simple
reader/writer model that can be used virtually on every platform.

The possible locks are LOCK_SH: Shared lock (reader). Allow other processes to access the file,
LOCK_EX: Exclusive lock.Prevent other processes from accessing file, LOCK_UN: Release a
shared or exclusive lock, and LOCK_NB: Avoids blocking other processes while locking.

24

You might also like