0% found this document useful (0 votes)
14 views98 pages

PDF&Rendition 1 1

PHP, or Hypertext Preprocessor, is a widely-used open-source server-side scripting language designed for web development, allowing dynamic content generation. It has evolved since its introduction in 1994, with significant versions enhancing performance and features, including support for object-oriented programming and database integration. PHP is easy to learn, integrates well with HTML, and is used in various applications, from content management systems to e-commerce platforms.
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)
14 views98 pages

PDF&Rendition 1 1

PHP, or Hypertext Preprocessor, is a widely-used open-source server-side scripting language designed for web development, allowing dynamic content generation. It has evolved since its introduction in 1994, with significant versions enhancing performance and features, including support for object-oriented programming and database integration. PHP is easy to learn, integrates well with HTML, and is used in various applications, from content management systems to e-commerce platforms.
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/ 98

PHP Introduction

The term PHP is an acronym for – Hypertext Preprocessor. PHP is a server-side scripting
language designed specifically for web development. It is an open-source which means it is
free to download and use. It is very simple to learn and use. The file extension of PHP is
“.php”.

What is PHP?

PHP is a server-side scripting language created primarily for web development but it is also
used as a general-purpose programming language. Unlike client-side languages like
JavaScript, which are executed on the user’s browser, PHP scripts run on the server. The
results are then sent to the client’s web browser as plain HTML.

History of PHP

PHP was introduced by Rasmus Lerdorf in 1994, the first version and participated in the later
versions. It is an interpreted language and it does not require a compiler. The language
quickly evolved and was given the name “PHP,” which initially named was “Personal Home
Page.”

 PHP 3 (1998): The first version considered suitable for widespread use.

 PHP 4 (2000): Improved performance and the introduction of the Zend Engine.

 PHP 5 (2004): Added object-oriented programming features.

 PHP 7 (2015): Significant performance improvements and reduced memory usage.

 PHP 8 (2020): Introduction of Just-In-Time (JIT) compilation, further enhancing


performance.

Characteristics of PHP
 PHP code is executed in the server.

 It can be integrated with many databases such as Oracle, Microsoft SQL Server,
MySQL, PostgreSQL, Sybase, and Informix.

 Websites like www.facebook.com and www.yahoo.com are also built on PHP.

 One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.

 The thing that differentiates PHP from the client-side language like HTML is, that
PHP codes are executed on the server whereas HTML codes are directly rendered on
the browser. PHP codes are first executed on the server and then the result is returned
to the browser.

 PHP files can support other client-side scripting languages like CSS and JavaScript.
How PHP Works?

Pr By P Mounika Lecturer in Computer Applications


PHP scripts are executed on the server. Here’s a typical flow of how PHP works:

 A user requests a PHP page via their web browser.

 The server processes the PHP code. The PHP interpreter parses the script, executes the
code, and generates HTML output.

 The server sends the generated HTML back to the client’s browser, which renders the
web page.

This server-side processing allows for dynamic content generation and ensures that sensitive
code is not exposed to the client.
Syntax

<?php

// PHP code goes here

?>

Basic Example of PHP

<!DOCTYPE html>

<html>

<head>

<title>PHP Hello World</title>

</head>

<body>

<?php echo "Hello, World! This is PHP code";?>


</body>

</html>

Output:

Hello, World! This is PHP code

Features of PHP

 Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.

Pr By P Mounika Lecturer in Computer Applications


 Cross-Platform: PHP runs on various platforms, making it compatible with different
operating systems.

 Database Integration: PHP provides built-in support for interacting with databases,
such as MySQL, PostgreSQL, and others.

 Server-Side Scripting: PHP scripts are executed on the server, generating HTML that
is sent to the client’s browser.

Applications of PHP

PHP is versatile and can be used in a variety of web development scenarios, including:
 Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.

 Content Management Systems (CMS): Many popular CMSs like WordPress, Joomla,
and Drupal are built with PHP.
 E-commerce Platforms: PHP is commonly used to develop e-commerce websites due
to its database integration capabilities.

 Web Applications: PHP is used for creating feature-rich web applications such as
social media platforms, forums, and customer relationship management (CRM)
systems.

 API Development: PHP can be used to create APIs for web and mobile applications.

Advantages of PHP

 Open Source: PHP is an open-source language, meaning it is freely available for


anyone to use and distribute. This openness has fostered a large and active community
of developers who continuously contribute to its growth, improvement, and feature
development.

 Easy to Learn: The syntax of PHP is quite similar to C and other programming
languages. This makes PHP relatively easy to learn, especially for developers who
already have some programming experience. Beginners find it approachable due to its
straightforward syntax and extensive online resources.
 Web Integration: PHP is designed specifically for web development and is embedded
within HTML. It seamlessly integrates with various web technologies, facilitating the
creation of dynamic and interactive web pages.

 Database Support: PHP has excellent support for various databases, including
MySQL, PostgreSQL, SQLite, and more. This makes it easy to connect and interact
with databases, a crucial aspect of many web applications.

 Cross-Platform Compatibility: PHP is platform-independent and runs on various


operating systems, including Windows, Linux, macOS, and others. This ensures
compatibility across different environments.

Pr By P Mounika Lecturer in Computer Applications


 Server-Side Scripting: PHP scripts are executed on the server, reducing the load on
the client’s side. This server-side scripting capability is crucial for generating dynamic
content and performing server-related tasks.

 Community Support: The PHP community actively contributes to the language’s


development, ensuring regular updates, security patches, and improvements.

Disadvantages of PHP

 Security Concerns: If not handled properly, PHP code may be susceptible to security
vulnerabilities, such as SQL injection and cross-site scripting (XSS). Developers need to
be cautious and follow best practices to secure PHP applications.

 Lack of Modern Features: Compared to newer languages, PHP may lack some modern
language features. However, recent versions of PHP have introduced improvements and
features to address this concern.

 Scalability Challenges: PHP can face challenges when it comes to scaling large and
complex applications. Developers may need to adopt additional tools or frameworks to
address scalability issues.

 Not Suitable for Large-Scale Applications: While PHP is suitable for small to medium-
sized projects, it might not be the best choice for extremely large and complex
applications where more structured languages might be preferred.

 Limited Object-Oriented Programming (OOP) Support: Although PHP supports OOP, its
implementation has been criticized for not being as robust as in some other languages.
However, recent versions have introduced improvements to enhance OOP capabilities.

PHP Variables
PHP Variables are one of the most fundamental concepts in programming. It is used to store
data that can be accessed and manipulated within your code. Variables in PHP are easy to use,
dynamically typed (meaning that you do not need to declare their type explicitly), and
essential for creating dynamic, interactive web applications.

Declaring Variables in PHP

To declare a variable in PHP, you simply assign a value to it using the $ symbol followed by
the variable name. PHP variables are case-sensitive and must start with a letter or an
underscore, followed by any number of letters, numbers, or underscores.

Example
<?php

Pr By P Mounika Lecturer in Computer Applications


$name = "XYZ"; // String

$age = 30; // Integer

$salary = 45000.50; // Float

$isEmployed = true; // Boolean

?>

Variable Naming Conventions

In PHP, it’s important to follow certain naming conventions for PHP variables to ensure
readability and maintainability:

 Start with a Letter or Underscore: Variable names must begin with a letter or an
underscore (_), not a number.

 Use Descriptive Names: Variable names should be descriptive of their purpose, e.g.,
$userName, $totalAmount.

 Case Sensitivity: PHP variable names are case-sensitive, meaning $name and $Name
are different variables.

 Avoid Reserved Words: Do not use PHP reserved words or keywords as variable
names (e.g., function, class, echo).

Example of Valid and Invalid Variable Names

<?php

$firstName = "Alice"; // Valid


$_age = 25; // Valid

$2ndPlace = "Bob"; // Invalid: Cannot start with a number

$class = "Physics"; // Valid, but avoid reserved words

?>

Data Types in PHP


 Integers: Integers are whole numbers without decimals, which can be positive or
negative.

 Doubles: Floats are numbers with decimal points or in exponential form.


 NULL: The NULL data type represents a variable with no value.

Pr By P Mounika Lecturer in Computer Applications


 Strings: Strings are sequences of characters, enclosed in single (‘ ‘) or double (” “)
quotes.

 Booleans: Booleans represent two possible values: true or false.


 Arrays: Arrays are used to store multiple values in a single variable. Arrays can be
indexed, associative, or multidimensional.

 Objects: Objects are instances of classes, which are templates for creating data
structures with properties and methods.

PHP Variable Scope


The scope of a variable refers to where it can be accessed within the code. PHP variables can
have local, global, static, or superglobal scope.

1. Local Scope or Local Variable

Variables declared within a function have local scope and cannot be accessed outside the
function. Any declaration of a variable outside the function with the same name (as within the
function) is a completely different variable.

Example: This example shows the local variable in PHP.

<?php

$num = 60;

function local_var() {

// This $num is local to this function

// The variable $num outside the function

// is a completely different

$num = 50;

echo "Variable num inside function is: $num \n";

local_var();

Pr By P Mounika Lecturer in Computer Applications


// The $num outside function is a completely

// different from inside local_var()

echo "Variable num outside function is: $num";

?>

Output

Variable num inside function is: 50

Variable num outside function is: 60

2. Global Scope or Global Variable

The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the
“global” keyword before the variable to refer to the global variable.

Example: This example shows the Global Variables in PHP.

<?php

$num = 20;

// Function to demonstrate use of global variable

function global_var() {

// We have to use global keyword before


// the variable $num to access within
// the function

global $num;

echo "Variable num inside function: $num \n";

global_var();

Pr By P Mounika Lecturer in Computer Applications


echo "Variable num outside function: $num \n";

?>

Output

Variable num inside function: 20

Variable num outside function: 20

PHP Arrays
An array stores multiple values in one single variable

An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name.

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index

 Associative arrays - Arrays with named keys

 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.

Example
Create and display an indexed array:

$cars = array("Volvo", "BMW", "Toyota");

var_dump($cars);

Output:

array(3) {

[0]=>

string(5) "Volvo"

Pr By P Mounika Lecturer in Computer Applications


[1]=>

string(4) "Ford"

[2]=>

string(6) "Toyota"

Access Indexed Arrays


To access an array item you can refer to the index number.

Example
Display the first array item:

$cars = array("Volvo", "BMW", "Toyota");

echo $cars[0];

Try it Yourself »

Volvo

Change Value
To change the value of an array item, use the index number:

Example
Change the value of the second item:

$cars = array("Volvo", "BMW", "Toyota");

$cars[1] = "Ford";

var_dump($cars);

Try it Yourself »

Pr By P Mounika Lecturer in Computer Applications


array(3) {

[0]=>

string(5) "Volvo"

[1]=>

string(4) "Ford"

[2]=>

string(6) "Toyota"

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use
a foreach loop, like this:

Example
Display all array items:

$cars = array("Volvo", "BMW", "Toyota");

foreach ($cars as $x) {

echo "$x <br>";

Try it Yourself »

Volvo
BMW
Toyota

Index Number
The key of an indexed array is a number, by default the first item is 0 and
the second is 1 etc., but there are exceptions.

Pr By P Mounika Lecturer in Computer Applications


New items get the next index number, meaning one higher than the highest
existing index.

So if you have an array like this:

$cars[0] = "Volvo";

$cars[1] = "BMW";

$cars[2] = "Toyota";

And if you use the array_push() function to add a new item, the new item will
get the index 3:

Example
array_push($cars, "Ford");

var_dump($cars);

Try it Yourself »
array(4) {

[0]=>

string(5) "Volvo"

[1]=>

string(3) "BMW"

[2]=>

string(6) "Toyota"

[3]=>

string(4) "Ford"

But if you have an array with random index numbers, like this:

$cars[5] = "Volvo";

$cars[7] = "BMW";

$cars[14] = "Toyota";

Pr By P Mounika Lecturer in Computer Applications


And if you use the array_push() function to add a new item, what will be the
index number of the new item?

Example
array_push($cars, "Ford");

var_dump($cars);

Try it Yourself »
The next array item gets the index 15:

array(4) {

[5]=>

string(5) "Volvo"

[7]=>

string(3) "BMW"

[14]=>

string(6) "Toyota"

[15]=>

string(4) "Ford"

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

ExampleGet your own PHP Server

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

Try it Yourself »

brand: Ford
model: Mustang
year: 1964

Pr By P Mounika Lecturer in Computer Applications


Access Associative Arrays

To access an array item you can refer to the key name.

Example

Display the model of the car:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

echo $car["model"];

Try it Yourself »

Mustang

Change Value

To change the value of an array item, use the key name:

Example

Change the year item:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

$car["year"] = 2024;

var_dump($car);

Try it Yourself »

array(3) {

["brand"]=>

string(4) "Ford"

Pr By P Mounika Lecturer in Computer Applications


["model"]=>

string(7) "Mustang"

["year"]=>

int(2024)

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like
this:

Example

Display all array items, keys and values:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

foreach ($car as $x => $y) {

echo "$x: $y <br>";

Try it Yourself »

brand: Ford
model: Mustang
year: 1964

PHP Multidimensional Arrays

Pr By P Mounika Lecturer in Computer Applications


A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.
 For a two-dimensional array you need two indices to select an element

 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of


arrays of arrays).

First, take a look at the following table:

Name Stock

Volvo 22

BMW 15

Saab 5

Land Rover 17

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row
and column.

To get access to the elements of the $cars array we must point to the two indices (row and
column):
Example

Pr By P Mounika Lecturer in Computer Applications


echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

Try it Yourself »

Volvo: In stock: 22, sold: 18.


BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

PHP Strings
PHP Strings are one of the most fundamental data types. It is used to handle text data,
manipulate user inputs, generate dynamic content, and much more. PHP provides a wide
array of functions and techniques for working with strings, making it easy to manipulate and
display text.

A string is a sequence of characters used to store and manipulate text data. PHP strings can
include letters, numbers, symbols, and special characters. Strings are a versatile data type,
commonly used for handling input/output, generating dynamic content, and more.

Declaration of String in PHP


Strings in PHP can be declared using single quotes, double quotes, heredoc, and nowdoc
syntax.

1. Single Quotes
Single quotes are used to define simple strings in PHP. The text within single quotes is treated
literally, meaning special characters and variables are not interpreted.

<?php

// Singlequote strings

$site = 'Welcome to GeeksforGeeks';

echo $site;

Pr By P Mounika Lecturer in Computer Applications


?>

Output

Welcome to GeeksforGeeks

The above program compiles correctly. We have created a string ‘Welcome to


GeeksforGeeks’ and stored it in variable and printing it using echo statement.
Let us now look at the below program:

<?php

// Single Quote Strings

$site = 'GeeksforGeeks';

echo 'Welcome to $site';

?>

Output

Welcome to $site

In the above program the echo statement prints the variable name rather than printing the
contents of the variables. This is because single-quotes strings in PHP do not process special
characters. Hence, the string is unable to identify the ‘$’ sign as the start of a variable name.

2. Double Quotes

Unlike single-quote strings, double-quote strings in PHP are capable of processing special
characters.
<?php

// Double Quote Strings

echo "Welcome to GeeksforGeeks \n";

Pr By P Mounika Lecturer in Computer Applications


$site = "GeeksforGeeks";

echo "Welcome to $site";

?>

Output

Welcome to GeeksforGeeks

Welcome to GeeksforGeeks

In the above program, we can see that the double-quote strings are processing the special
characters according to their properties. The ‘\n’ character is not printed and is considered as
a new line. Also instead of the variable name $site, “GeeksforGeeks” is printed.

Note: PHP treats everything inside double quotes(” “) as Strings.

<?php

$name = "Krishna";

echo "The name of the geek is $name \n";

echo 'The name of the geek is $name';

?>

Output

The name of the geek is Krishna

The name of the geek is $name

Some important and frequently used special characters that are used with double-quoted
strings are explained below:

The character begins with a backslash(“\”) is treated as escape sequences and is replaced with
special characters. Here are few important escape sequences.

 “\n” is replaced by a new line

 “\t” is replaced by a tab space


Some Important Built-in String Functions

Pr By P Mounika Lecturer in Computer Applications


PHP built-in functions are some existing library functions that can be used directly in our
programs making an appropriate call to them. Below are some important built-in string
functions that we use in our daily and regular programs:

1. PHP strlen() Function

This function is used to find the length of a string. This function accepts the string as an
argument and returns the length or number of characters in the string.

<?php

echo strlen("Hello GeeksforGeeks!");

?>

Output

20

2. PHP strrev() Function

This function is used to reverse a string. This function accepts a string as an argument and
returns its reversed string.

<?php

echo strrev("Hello GeeksforGeeks!");

?>

Output

!skeeGrofskeeG olleH

3. PHP str_replace() Function

This function takes three strings as arguments. The third argument is the original string and
the first argument is replaced by the second one. In other words, we can say that it replaces
all occurrences of the first argument in the original string with the second argument.

<?php

echo str_replace("Geeks", "World", "Hello GeeksforGeeks!"), "\n";

Pr By P Mounika Lecturer in Computer Applications


echo str_replace("for", "World", "Hello GeeksforGeeks!"), "\n";

?>

Output

Hello WorldforWorld!

Hello GeeksWorldGeeks!

In the first example, we can see that all occurrences of the word “Geeks” are replaced by
“World” in “Hello GeeksforGeeks!”.

4. PHP strpos() Function

This function takes two string arguments and if the second string is present in the first one, it
will return the starting position of the string otherwise returns FALSE.

<?php

echo strpos("Hello GeeksforGeeks!", "Geeks"), "\n";

echo strpos("Hello GeeksforGeeks!", "for"), "\n";

var_dump(strpos("Hello GeeksforGeeks!", "Peek"));

?>

Output

11

bool(false)

We can see in the above program, in the third example the string “Peek” is not present in the
first string, hence this function returns a boolean value false indicating that string is not
present.

5. PHP strtolower() Function


This function converts a string into the lowercase string.

Pr By P Mounika Lecturer in Computer Applications


<?php

$input = "WELCOME TO GEEKSFORGEEKS";

echo strtolower($input);

?>

Output

welcome to geeksforgeeks

8. PHP strtoupper() Function


This function converts a string into the uppercase string.

<?php

$input = "Welcome to geeksforgeeks";

echo strtoupper($input);

?>

Output

WELCOME TO GEEKSFORGEEKS

9. PHP strwordcount() Function

This function counts total words in a string.

<?php

$input = "Welcome to GeeksforGeeks";

echo str_word_count($input);

Pr By P Mounika Lecturer in Computer Applications


?>

Output
3

PHP Operators
Operators are used to performing operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them, and gives a
result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1
and 2, performs an addition operation on them to give 3.

Just like any other programming language, PHP also supports various types of operations like
arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc),
Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform
such operations on various operands or variables, or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are the various groups
of operators:

 Arithmetic Operators

 Logical or Relational Operators

 Comparison Operators

 Conditional or Ternary Operators

 Assignment Operators

 Spaceship Operators (Introduced in PHP 7)

 Array Operators

 Increment/Decrement Operators

 String Operators
Let us now learn about each of these operators in detail.

Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their
syntax and operations in PHP.

Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

Pr By P Mounika Lecturer in Computer Applications


Operator Name Syntax Operation

– Subtraction $x – $y Differences the operands

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Note: The exponentiation has been introduced in PHP 5.6.

Example: This example explains the arithmetic operator in PHP.

<?php

// Define two numbers

$x = 10;

$y = 3;

// Addition

echo "Addition: " . ($x + $y) . "\n";

// Subtraction

echo "Subtraction: " . ($x - $y) . "\n";

// Multiplication

echo "Multiplication: " . ($x * $y) . "\n";

// Division
echo "Division: " . ($x / $y) . "\n";

Pr By P Mounika Lecturer in Computer Applications


// Exponentiation

echo "Exponentiation: " . ($x ** $y) . "\n";

// Modulus

echo "Modulus: " . ($x % $y) . "\n";

?>

Output
Addition: 13

Subtraction: 7
Multiplication: 30

Division: 3.3333333333333

Exponentiation: 1000

Modulus: 1

Logical or Relational Operators:


These are basically used to operate with conditional statements and expressions. Conditional
statements are based on conditions. Also, a condition can either be met or cannot be met so
the result of a conditional statement can either be true or false. Here are the logical operators
along with their syntax and operations in PHP.

Operator Name Syntax Operation

Logical $x and
and True if both the operands are true else false
AND $y

or Logical OR $x or $y True if either of the operands is true else false

Logical True if either of the operands is true and false if


xor $x xor $y
XOR both are true

Pr By P Mounika Lecturer in Computer Applications


Operator Name Syntax Operation

Logical $x &&
&& True if both the operands are true else false
AND $y

|| Logical OR $x || $y True if either of the operands is true else false

Logical
! !$x True if $x is false
NOT

Example: This example describes the logical & relational operator in PHP.

<?php
$x = 50;

$y = 30;

if ($x == 50 and $y == 30)

echo "and Success \n";

if ($x == 50 or $y == 20)

echo "or Success \n";

if ($x == 50 xor $y == 20)

echo "xor Success \n";

if ($x == 50 && $y == 30)

echo "&& Success \n";

if ($x == 50 || $y == 20)

echo "|| Success \n";

if (!$z)

Pr By P Mounika Lecturer in Computer Applications


echo "! Success \n";

?>

Output:

and Success
or Success
xor Success
&& Success
|| Success
! Success

Comparison Operators: These operators are used to compare two elements and outputs the
result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.

Operator Name Syntax Operation

== Equal To $x == $y Returns True if both the operands are equal

Returns True if both the operands are not


!= Not Equal To $x != $y
equal

<> Not Equal To $x <> $y Returns True if both the operands are unequal

$x === Returns True if both the operands are equal


=== Identical
$y and are of the same type

Returns True if both the operands are unequal


!== Not Identical $x == $y
and are of different types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

Less Than or
<= $x <= $y Returns True if $x is less than or equal to $y
Equal To

Pr By P Mounika Lecturer in Computer Applications


Operator Name Syntax Operation

Greater Than or Returns True if $x is greater than or equal to


>= $x >= $y
Equal To $y

Example: This example describes the comparison operator in PHP.

<?php
$a = 80;

$b = 50;

$c = "80";

// Here var_dump function has been used to

// display structured information. We will learn

// about this function in complete details in further

// articles.

var_dump($a == $c) + "\n";

var_dump($a != $b) + "\n";

var_dump($a <> $b) + "\n";

var_dump($a === $c) + "\n";

var_dump($a !== $c) + "\n";

var_dump($a < $b) + "\n";


var_dump($a > $b) + "\n";

var_dump($a <= $b) + "\n";

var_dump($a >= $b);

?>

Output:

bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

Pr By P Mounika Lecturer in Computer Applications


bool(false)
bool(true)
bool(false)
bool(true)

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. These are also used as a shorthand
notation for if…else statement that we will read in the article on decision making.

Syntax:

$var = (condition)? value1 : value2;

Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

Operator Name Operation

If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted
otherwise the result is on right.

Example: This example describes the Conditional or Ternary operators in PHP.

<?php

$x = -12;

echo ($x > 0) ? 'The number is positive' : 'The number is negative';

?>

Output:

The number is negative

Assignment Operators: These operators are used to assign values to different variables, with
or without mid-operations. Here are the assignment operators along with their syntax and
operations, that PHP provides for the operations.

Operator Name Syntax Operation

Operand on the left obtains the value of


= Assign $x = $y
the operand on the right

Pr By P Mounika Lecturer in Computer Applications


Operator Name Syntax Operation

$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y

-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y

$x *=
*= Multiply then Assign Simple product same as $x = $x * $y
$y

Divide then Assign


/= $x /= $y Simple division same as $x = $x / $y
(quotient)

Divide then Assign $x %=


%= Simple division same as $x = $x % $y
(remainder) $y

Example: This example describes the assignment operator in PHP.

<?php

// Simple assign operator

$y = 75;

echo $y, "\n";

// Add then assign operator

$y = 100;

$y += 200;

echo $y, "\n";

// Subtract then assign operator


$y = 70;

$y -= 10;
echo $y, "\n";

Pr By P Mounika Lecturer in Computer Applications


// Multiply then assign operator

$y = 30;

$y *= 20;

echo $y, "\n";

// Divide then assign(quotient) operator

$y = 100;
$y /= 5;

echo $y, "\n";

// Divide then assign(remainder) operator

$y = 50;

$y %= 5;

echo $y;

?>

Output:

75
300
60
600
20
0

Array Operators: These operators are used in the case of arrays. Here are the array
operators along with their syntax and operations, that PHP provides for the array operation.

Operator Name Syntax Operation

+ Union $x + $y Union of both i.e., $x and $y

$x ==
== Equality Returns true if both has same key-value pair
$y

Pr By P Mounika Lecturer in Computer Applications


Operator Name Syntax Operation

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value pair in


=== Identity
$y the same order and of the same type

Non- $x !==
!== Returns True if both are not identical to each other
Identity $y

$x <>
<> Inequality Returns True if both are unequal
$y

Example: This example describes the array operation in PHP.

<?php

$x = array("k" => "Car", "l" => "Bike");

$y = array("a" => "Train", "b" => "Plane");

var_dump($x + $y);

var_dump($x == $y) + "\n";

var_dump($x != $y) + "\n";

var_dump($x <> $y) + "\n";

var_dump($x === $y) + "\n";

var_dump($x !== $y) + "\n";


?>

Output:

array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"

Pr By P Mounika Lecturer in Computer Applications


["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

Increment/Decrement Operators: These are called the unary operators as they work on
single operands. These are used to increment or decrement values.

Operator Name Syntax Operation

++ Pre-Increment ++$x First increments $x by one, then return $x

— Pre-Decrement –$x First decrements $x by one, then return $x

++ Post-Increment $x++ First returns $x, then increment it by one

— Post-Decrement $x– First returns $x, then decrement it by one

Example: This example describes the Increment/Decrement operators in PHP.

<?php

$x = 2;

echo ++$x, " First increments then prints \n";

echo $x, "\n";

$x = 2;

echo $x++, " First prints then increments \n";

echo $x, "\n";

$x = 2;
echo --$x, " First decrements then prints \n";

echo $x, "\n";

Pr By P Mounika Lecturer in Computer Applications


$x = 2;

echo $x--, " First prints then decrements \n";

echo $x;

?>

Output:

3 First increments then prints


3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1

String Operators: This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.

Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then assigns, same as


.= $x.=$y
assignment $x = $x.$y

Example: This example describes the string operator in PHP.

<?php

$x = "Geeks";

$y = "for";

$z = "Geeks!!!";

echo $x . $y . $z, "\n";


$x .= $y . $z;

echo $x;
?>

Pr By P Mounika Lecturer in Computer Applications


Output:

GeeksforGeeks!!!
GeeksforGeeks!!!

Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used to
compare values but instead of returning the boolean results, it returns integer values. If both
the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left
operand is greater, it returns 1. The following table shows how it works in detail:

Operator Syntax Operation

$x <=>
$x < $y Identical to -1 (right is greater)
$y

$x <=>
$x > $y Identical to 1 (left is greater)
$y

$x <= $x <=> Identical to -1 (right is greater) or identical to 0 (if both are


$y $y equal)

$x >= $x <=> Identical to 1 (if left is greater) or identical to 0 (if both are
$y $y equal)

$x == $x <=>
Identical to 0 (both are equal)
$y $y

$x <=>
$x != $y Not Identical to 0
$y

Example: This example illustrates the use of the spaceship operator in PHP.

<?php

$x = 50;
$y = 50;
$z = 25;

Pr By P Mounika Lecturer in Computer Applications


echo $x <=> $y;

echo "\n";

echo $x <=> $z;

echo "\n";

echo $z <=> $y;


echo "\n";

// We can do the same for Strings

$x = "Ram";

$y = "Krishna";

echo $x <=> $y;

echo "\n";

echo $x <=> $y;

echo "\n";

echo $y <=> $x;


?>

Output:
0
1
-1
1
1
-1

Pr By P Mounika Lecturer in Computer Applications


PHP Expressions
Introduction

Almost everything in a PHP script is an expression. Anything that has a value is an


expression. In a typical assignment statement ($x=100), a literal value, a function or operands
processed by operators is an expression, anything that appears to the right of assignment
operator (=)

Syntax

$x=100; //100 is an expression

$a=$b+$c; //b+$c is an expression

$c=add($a,$b); //add($a,$b) is an expresson

$val=sqrt(100); //sqrt(100) is an expression

$var=$x!=$y; //$x!=$y is an expression

expression with ++ and -- operators

These operators are called increment and decrement operators respectively. They are unary
operators, needing just one operand and can be used in prefix or postfix manner, although
with different effect on value of expression

Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator
decrements by 1). However, when used in assignment expression, prefix
makesincremnt/decrement first and then followed by assignment. In case of postfix,
assignment is done before increment/decrement

Uses postfix ++ operator

Example

Live Demo

<?php

$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1

echo "x = $x y = $y";


?>

Pr By P Mounika Lecturer in Computer Applications


Output

This produces following result

x = 11 y = 10

Whereas following example uses prefix increment operator in assignment

Example

Live Demo

<?php

$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x

echo "x = $x y = $y";

?>

Output

This produces following result

x = 11 y = 11

Expression with Ternary conditional operator

Ternary operator has three operands. First one is a logical expression. If it is TRU, second
operand expression is evaluated otherwise third one is evaluated

Example
Live Demo

<?php

$marks=60;

$result= $marks<50 ? "fail" : "pass";

echo $result;

?>

Output

Following result will be displayed

Pass

PHP Control Structures and Loops: if, else, for, foreach, while

Pr By P Mounika Lecturer in Computer Applications


In simple terms, a control structure allows you to control the flow of code execution in your
application. Generally, a program is executed sequentially, line by line, and a control structure
allows you to alter that flow, usually depending on certain conditions.

Control structures are core features of the PHP language that allow your script to respond
differently to different inputs or situations. This could allow your script to give different
responses based on user input, file contents, or some other data.

The following flowchart explains how a control structure works in PHP.

As you can see in the above diagram, first a condition is checked. If the condition is true, the
conditional code will be executed. The important thing to note here is that code execution
continues normally after conditional code execution.

Let's consider the following example.

Pr By P Mounika Lecturer in Computer Applications


In the above example, the program checks whether or not the user is logged in. Based on the
user's login status, they will be redirected to either the Login page or the My Account page.
In this case, a control structure ends code execution by redirecting users to a different page.
This is a crucial ability of the PHP language.
PHP supports a number of different control structures:

 if

 else

 elseif

 switch

 while

 do-while

 for

 foreach

 and more

Let's take a look at a few of these control structures with examples.

Learning PHP Control Structures

Pr By P Mounika Lecturer in Computer Applications


In the previous section, we learned the basics of control structures in PHP and their
usefulness in application development. In this section, we'll go through a couple of important
control structures that you'll end up using frequently in your day-to-day application
development.

PHP If Statement
The if construct allows you to execute a piece of code if the expression provided along with it
evaluates to true.

Let's have a look at the following example to understand how it actually works.

<?php
1

$age = 50;
2

if ($age > 30)


4

{
5

echo "Your age is greater than 30!";


6

}
7

?>
8

The above example should output the Your age is greater than 30! message since the
expression evaluates to true. In fact, if you want to execute only a single statement, the above
example can be rewritten without brackets, as shown in the following snippet.

1 <?php

Pr By P Mounika Lecturer in Computer Applications


$age = 50;
2

if ($age > 30)


4

echo "Your age is greater than 30!";


5

?>
6

On the other hand, if you have more than one statement to execute, you must use brackets, as
shown in the following snippet.

<?php
1

if (is_array($user))
2

{
3

$user_id = isset($user['user_id']) ? $user['user_id'] : '';


4

$username = isset($user['username']) ? $user['username'] : '';


5

// and more statements...


6

Pr By P Mounika Lecturer in Computer Applications


}
7

?>
8

PHP Else Statement


In the previous section, we discussed the if construct, which allows you to execute a piece of
code if the expression evaluates to true. On the other hand, if the expression evaluates to
false, it won't do anything. More often than not, you also want to execute a different code
snippet if the expression evaluates to false. That's where the else statement comes into the
picture.

You always use the else statement in conjunction with an if statement. Basically, you can
define it as shown in the following pseudo-code.

if (expression)
1

{
2

// code is executed if the expression evaluates to TRUE


3

}
4

else
5

{
6

// code is executed if the expression evaluates to FALSE


7

8 }

Pr By P Mounika Lecturer in Computer Applications


Let's revise the previous example to understand how it works.

<?php
1

$age = 50;
2

if ($age < 30)


4

{
5

echo "Your age is less than 30!";


6

}
7

else
8

{
9

echo "Your age is greater than or equal to 30!";


10

}
11

12 ?>

Pr By P Mounika Lecturer in Computer Applications


So when you have two choices, and one of them must be executed, you can use the if-
else construct.

Advertisement

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

Let's study the basic structure of the elseif statement, as shown in the following pseudo-code.

if (expression1)
1

{
2

// code is executed if the expression1 evaluates to TRUE


3

}
4

elseif (expression2)
5

{
6

// code is executed if the expression2 evaluates to TRUE


7

}
8

elseif (expression3)
9

Pr By P Mounika Lecturer in Computer Applications


{
10

// code is executed if the expression3 evaluates to TRUE


11

}
12

else
13

{
14

// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a default cho
15

}
16

Again, let's try to understand it using a real-world example.

<?php
1

$age = 50;
2

if ($age < 30)


4

{
5

Pr By P Mounika Lecturer in Computer Applications


echo "Your age is less than 30!";
6

}
7

elseif ($age > 30 && $age < 40)


8

{
9

echo "Your age is between 30 and 40!";


10

}
11

elseif ($age > 40 && $age < 50)


12

{
13

echo "Your age is between 40 and 50!";


14

}
15

else
16

{
17

Pr By P Mounika Lecturer in Computer Applications


echo "Your age is greater than 50!";
18

}
19

?>
20

As you can see in the above example, we have multiple conditions, so we've used a series
of elseif statements. In the event that all if conditions evaluate to false, it executes the code
provided in the last else statement.

PHP Switch Statement


The switch statement is somewhat similar to the elseif statement which we've just discussed
in the previous section. The only difference is the expression which is being checked.
In the case of the elseif statement, you have a set of different conditions, and an appropriate
action will be executed based on a condition. On the other hand, if you want to compare a
variable with different values, you can use the switch statement.

As usual, an example is the best way to understand the switch statement.

<?php
1

$favourite_site = 'Code';
2

switch ($favourite_site) {
4

case 'Business':
5

echo "My favourite site is business.tutsplus.com!";


6

Pr By P Mounika Lecturer in Computer Applications


break;
7

case 'Code':
8

echo "My favourite site is code.tutsplus.com!";


9

break;
10

case 'Web Design':


11

echo "My favourite site is webdesign.tutsplus.com!";


12

break;
13

case 'Music':
14

echo "My favourite site is music.tutsplus.com!";


15

break;
16

case 'Photography':
17

echo "My favourite site is photography.tutsplus.com!";


18

Pr By P Mounika Lecturer in Computer Applications


break;
19

default:
20

echo "I like everything at tutsplus.com!";


21

}
22

?>
23

As you can see in the above example, we want to check the value of
the $favourite_site variable, and based on the value of the $favourite_site variable, we want
to print a message.
For each value you want to check with the $favourite_site variable, you have to define
the case block. If the value is matched with a case, the code associated with that case block
will be executed. After that, you need to use the break statement to end code execution. If you
don't use the break statement, script execution will be continued up to the last block in the
switch statement.

Finally, if you want to execute a piece of code if the variable's value doesn't match any case,
you can define it under the default block. Of course, it's not mandatory—it's just a way to
provide a default case.

So that's the story of conditional control structures. We'll discuss loops in PHP in the next
section.
Loops in PHP
Loops in PHP are useful when you want to execute a piece of code repeatedly until a
condition evaluates to false. So code is executed repeatedly as long as a condition evaluates
to true, and as soon as the condition evaluates to false, the script continues executing the code
after the loop.

The following flowchart explains how loops work in PHP.

Pr By P Mounika Lecturer in Computer Applications


As you can see in the above screenshot, a loop contains a condition. If the condition evaluates
to true, the conditional code is executed. After execution of the conditional code, control goes
back to the loop condition, and the flow continues until the condition evaluates to false.

In this section, we'll go through the different types of loops supported in PHP.

Advertisement

While Loop in PHP


The while loop is used when you want to execute a piece of code repeatedly until
the while condition evaluates to false.

You can define it as shown in the following pseudo-code.

while (expression)
1

{
2

// code to execute as long as expression evaluates to TRUE


3

Pr By P Mounika Lecturer in Computer Applications


}
4

Let's have a look at a real-world example to understand how the while loop works in PHP.

<?php
1

$max = 0;
2

echo $i = 0;
3

echo ",";
4

echo $j = 1;
5

echo ",";
6

$result=0;
7

while ($max < 10 )


9

{
10

$result = $i + $j;
11

Pr By P Mounika Lecturer in Computer Applications


12

$i = $j;
13

$j = $result;
14

15

$max = $max + 1;
16

echo $result;
17

echo ",";
18

}
19

?>
20

If you're familiar with the Fibonacci series, you might recognize what the above program
does—it outputs the Fibonacci series for the first ten numbers. The while loop is generally
used when you don't know the number of iterations that are going to take place in a loop.

Do-While Loop in PHP


The do-while loop is very similar to the while loop, with the only difference being that the
while condition is checked at the end of the first iteration. Thus, we can guarantee that the
loop code is executed at least once, irrespective of the result of the while expression.

Let's have a look at the syntax of the do-while loop.

do
1

Pr By P Mounika Lecturer in Computer Applications


{
2

// code to execute
3

} while (expression);
4

Let's go through a real-world to understand possible cases where you can use the do-
while loop.

<?php
1

$handle = fopen("file.txt", "r");


2

if ($handle)
3

{
4

do
5

{
6

$line = fgets($handle);
7

// process the line content


9

Pr By P Mounika Lecturer in Computer Applications


10

} while($line !== false);


11

}
12

fclose($handle);
13

?>
14

In the above example, we're trying to read a file line by line. Firstly, we've opened a file for
reading. In our case, we're not sure if the file contains any content at all. Thus, we need to
execute the fgets function at least once to check if a file contains any content. So we can use
the do-while loop here. do-while evaluates the condition after the first iteration of the loop.

For Loop in PHP


Generally, the for loop is used to execute a piece of code a specific number of times. In other
words, if you already know the number of times you want to execute a block of code, it's
the for loop which is the best choice.

Let's have a look at the syntax of the for loop.

for (expr1; expr2; expr3)


1

{
2

// code to execute
3

}
4

The expr1 expression is used to initialize variables, and it's always executed.
The expr2 expression is also executed at the beginning of a loop, and if it evaluates to true,

Pr By P Mounika Lecturer in Computer Applications


the loop code is executed. After execution of the loop code, the expr3 is executed. Generally,
the expr3 is used to alter the value of a variable which is used in the expr2 expression.

Let's go through the following example to see how it works.

<?php
1

for ($i=1; $i<=10; ++$i)


2

{
3

echo sprintf("The square of %d is %d.</br>", $i, $i*$i);


4

}
5

?>
6

The above program outputs the square of the first ten numbers. It initializes $i to 1, repeats as
long as $i is less than or equal to 10, and adds 1 to $i at each iteration.

For Each in PHP


The foreach loop is used to iterate over array variables. If you have an array variable, and you
want to go through each element of that array, the foreach loop is the best choice.

Let's have a look at a couple of examples.

<?php
1

$fruits = array('apple', 'banana', 'orange', 'grapes');


2

3 foreach ($fruits as $fruit)

Pr By P Mounika Lecturer in Computer Applications


{
4

echo $fruit;
5

echo "<br/>";
6

}
7

$employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Engineer');
9

foreach ($employee as $key => $value)


10

{
11

echo sprintf("%s: %s</br>", $key, $value);


12

echo "<br/>";
13

}
14

?>
15

Pr By P Mounika Lecturer in Computer Applications


If you want to access array values, you can use the first version of the foreach loop, as shown
in the above example. On the other hand, if you want to access both a key and a value, you
can do it as shown in the $employee example above.

Breaking Out of the Loop


There are times when you might want to break out of a loop before it runs its course. This can
be achieved easily using the break keyword. It will get you out of the
current for, foreach, while, do-while, or switch structure.

You can also use break to get out of multiple nested loops by supplying a numeric argument.
For example, using break 3 will break you out of 3 nested loops. However, you cannot pass a
variable as the numeric argument if you are using a PHP version greater than or equal to 5.4.

<?php
1

echo 'Simple Break';


3

for($i = 1; $i <= 2; $i++) {


4

echo "\n".'$i = '.$i.' ';


5

for($j = 1; $j <= 5; $j++) {


6

if($j == 2) {
7

break;
8

}
9

Pr By P Mounika Lecturer in Computer Applications


echo '$j = '.$j.' ';
10

}
11

}
12

13

/*
14

Simple Break
15

i=1j=1
16

i=2j=1
17

*/
18

19

echo 'Multi-level Break';


20

for($i = 1; $i <= 2; $i++) {


21

echo "\n".'$i = '.$i.' ';


22

Pr By P Mounika Lecturer in Computer Applications


for($j = 1; $j <= 5; $j++) {
23

if($j == 2) {
24

break 2;
25

}
26

echo '$j = '.$j.' ';


27

}
28

}
29

30

/*
31

Multi-level Break
32

i=1j=1
33

*/
34

35

Pr By P Mounika Lecturer in Computer Applications


?>
36

Another keyword that can interrupt loops in PHP is continue. However, this only skips the
rest of the current loop iteration instead of breaking out of the loop altogether. Just like break,
you can also use a numerical value with continue to specify how many nested loops it should
skip for the current iteration.

<?php
1

echo 'Simple Continue';


3

for($i = 1; $i <= 2; $i++) {


4

echo "\n".'$i = '.$i.' ';


5

for($j = 1; $j <= 5; $j++) {


6

if($j == 2) {
7

continue;
8

}
9

echo '$j = '.$j.' ';


10

Pr By P Mounika Lecturer in Computer Applications


}
11

}
12

13

/*
14

Simple Continue
15

i=1j=1j=3j=4j=5
16

i=2j=1j=3j=4j=5
17

*/
18

19

echo 'Multi-level Continue';


20

for($i = 1; $i <= 2; $i++) {


21

echo "\n".'$i = '.$i.' ';


22

for($j = 1; $j <= 5; $j++) {


23

Pr By P Mounika Lecturer in Computer Applications


if($j == 2) {
24

continue 2;
25

}
26

echo '$j = '.$j.' ';


27

}
28

}
29

30

/*
31

Multi-level Continue
32

i=1j=1
33

i=2j=1
34

*/
35

36

Pr By P Mounika Lecturer in Computer Applications


37 ?>

PHP | Functions
A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better understanding of
how functions work. Suppose the boss wants his employee to calculate the annual budget. So
how will this process complete? The employee will take information about the statistics from
the boss, performs calculations and calculate the budget and shows the result to his boss.
Functions works in a similar manner. They take informations as parameter, executes a block
of statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:

 Built-in functions : PHP provides us with huge collection of built-in library


functions. These functions are already coded and stored in form of functions. To use
those we just need to call them as per our requirement like, var_dump, fopen(),
print_r(), gettype() and so on.

 User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.

Why should we use functions?

 Reusability: If we have a common code that we would like to use at various parts of
a program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program

 Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.

 Easily maintained: As we have used functions in our program, so if anything or any


line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.

Pr By P Mounika Lecturer in Computer Applications


Creating a Function

While creating a user defined function we need to keep few things in mind:

1. Any name ending with an open and closed parenthesis is a function.

2. A function name always begins with the keyword function.


3. To call a function we just need to write its name followed by the parenthesis

4. A function name cannot start with a number. It can start with an alphabet or
underscore.

5. A function name is not case-sensitive.

Syntax:

function function_name(){
executable code;
}

Example:

<?php

function funcGeek()

echo "This is Geeks for Geeks";

// Calling the function

funcGeek();

?>

Pr By P Mounika Lecturer in Computer Applications


Output:

This is Geeks for Geeks

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are called parameters. These
are used to hold the values executable during runtime. A user is free to take in as many
parameters as he wants, separated with a comma(,) operator. These parameters are used to
accept inputs during runtime. While passing the values like during a function call, they are
called arguments. An argument is a value passed to a function and a parameter is used to hold
those arguments. In common term, both parameter and argument mean the same. We need to
keep in mind that for every parameter, we need to pass its corresponding argument.
Syntax:

function function_name($first_parameter, $second_parameter) {


executable code;
}

Example:

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

echo "The product is $product";

// Calling the function

// Passing three arguments


proGeek(2, 3, 5);

Pr By P Mounika Lecturer in Computer Applications


?>

Output:

The product is 30

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:

<?php

// function with default parameter

function defGeek($str, $num=12)


{

echo "$str is $num years old \n";

// Calling the function

defGeek("Ram", 15);

// In this call, the default value 12

// will be considered

defGeek("Adam");

?>
Output:

Pr By P Mounika Lecturer in Computer Applications


Ram is 15 years old
Adam is 12 years old

In the above example, the parameter $num has a default value 12, if we do not pass any value
for this parameter in a function call then this default value 12 will be considered. Also the
parameter $str has no default value , so it is compulsory.

Returning Values from Functions

Functions can also return values to the part of program from where it is called.
The return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The return
statement also marks the end of the function and stops the execution after that and returns the
value.
Example:

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

return $product; //returning the product

// storing the returned value

$retValue = proGeek(2, 3, 5);

echo "The product is $retValue";

?>

Output:

Pr By P Mounika Lecturer in Computer Applications


The product is 30

Parameter passing to Functions

PHP allows us two ways in which an argument can be passed into a function:

 Pass by Value: On passing arguments using pass by value, the value of the argument
gets changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an argument.

 Pass by Reference: On passing arguments as pass by reference, the original value is


passed. Therefore, the original value gets altered. In pass by reference we actually
pass the address of the value, where it is stored using ampersand sign(&).

Example:

<?php

// pass by value

function valGeek($num) {

$num += 2;

return $num;

// pass by reference

function refGeek(&$num) {

$num += 10;

return $num;

$n = 10;

Pr By P Mounika Lecturer in Computer Applications


valGeek($n);

echo "The original value is still $n \n";

refGeek($n);

echo "The original value changes to $n";

?>

Output:

The original value is still 10


The original value changes to 20

READING DATA FROM WEB FORM CONTROLS LIMKE TEXT


BOXES ,RADIO BUTTONS,LISTS
HTML forms are used to send the user information to the server and returns the result back to
the browser. For example, if you want to get the details of visitors to your website, and send
them good thoughts, you can collect the user information by means of form processing. Then,
the information can be validated either at the client-side or on the server-side. The final result
is sent to the client through the respective web browser. To create a HTML form, form tag
should be used.

Attributes of Form Tag:

Attribute Description

name or
It specifies the name of the form and is used to identify individual forms.
id

It specifies the location to which the form data has to be sent when the form
action
is submitted.

It specifies the HTTP method that is to be used when the form is submitted.
method The possible values are get and post. If get method is used, the form data are
visible to the users in the url. Default HTTP method is get.

Pr By P Mounika Lecturer in Computer Applications


encType It specifies the encryption type for the form data when the form is submitted.

novalidate It implies the server not to verify the form data when the form is submitted.

Controls used in forms: Form processing contains a set of controls through which the client
and server can communicate and share information. The controls used in forms are:

 Textbox: Textbox allows the user to provide single-line input, which can be used for
getting values such as names, search menu and etc.

 Textarea: Textarea allows the user to provide multi-line input, which can be used for
getting values such as an address, message etc.

 DropDown: Dropdown or combobox allows the user to provide select a value from a
list of values.

 Radio Buttons: Radio buttons allow the user to select only one option from the given
set of options.

 CheckBox: Checkbox allows the user to select multiple options from the set of given
options.

 Buttons: Buttons are the clickable controls that can be used to submit the form.

Creating a simple HTML Form: All the form controls given above is designed by using
the input tag based on the type attribute of the tag. In the below script, when the form is
submitted, no event handling mechanism is done. Event handling refers to the process done
while the form is submitted. These event handling mechanisms can be done by using
javaScript or PHP. However, JavaScript provides only client-side validation. Hence, we can
use PHP for form processing.

HTML Code:

<!DOCTYPE html>

<html>

<head>
<title>Simple Form Processing</title>

</head>

<body>

Pr By P Mounika Lecturer in Computer Applications


<form id="form1" method="post">

FirstName:

<input type="text" name="firstname" required/>

<br>

<br>
LastName

<input type="text" name="lastname" required/>

<br>

<br>

Address

<input type="text" name="address" required/>

<br>

<br>

Email Address:

<input type="email" name="emailaddress" required/>

<br>

<br>

Password:

<input type="password" name="password" required/>


<br>

<br>

<input type="submit" value="Submit”/>

</form>

</body>

</html>

Form Validation: Form validation is done to ensure that the user has provided the relevant
information. Basic validation can be done using HTML elements. For example, in the above
script, the email address text box is having a type value as “email”, which prevents the user
from entering the incorrect value for an email. Every form field in the above script is

Pr By P Mounika Lecturer in Computer Applications


followed by a required attribute, which will intimate the user not to leave any field empty
before submitting the form. PHP methods and arrays used in form processing are:

 isset(): This function is used to determine whether the variable or a form control is
having a value or not.

 $_GET[]: It is used the retrieve the information from the form control through the
parameters sent in the URL. It takes the attribute given in the url as the parameter.

 $_POST[]: It is used the retrieve the information from the form control through the
HTTP POST method. IT takes name attribute of corresponding form control as the
parameter.

 $_REQUEST[]: It is used to retrieve an information while using a database.

Form Processing using PHP: Above HTML script is rewritten using the above mentioned
functions and array. The rewritten script validates all the form fields and if there are no errors,
it displays the received information in a tabular form.

 Example:

<?php
if (isset($_POST['submit']))

if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||

(!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||

(!isset($_POST['password'])) || (!isset($_POST['gender'])))

$error = "*" . "Please fill all the required fields";

else

$firstname = $_POST['firstname'];

$lastname = $_POST['lastname'];

$address = $_POST['address'];

$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];

Pr By P Mounika Lecturer in Computer Applications


$gender = $_POST['gender'];

?>

<html>

<head>

<title>Simple Form Processing</title>

</head>

<body>

<h1>Form Processing using PHP</h1>

<fieldset>

<form id="form1" method="post" action="form.php">

<?php

if (isset($_POST['submit']))

if (isset($error))

{
echo "<p style='color:red;'>"

. $error . "</p>";

?>

FirstName:

<input type="text" name="firstname"/>

<span style="color:red;">*</span>

Pr By P Mounika Lecturer in Computer Applications


<br>

<br>

Last Name:

<input type="text" name="lastname"/>

<span style="color:red;">*</span>
<br>

<br>

Address:

<input type="text" name="address"/>

<span style="color:red;">*</span>

<br>

<br>

Email:

<input type="email" name="emailaddress"/>

<span style="color:red;">*</span>

<br>

<br>

Password:

<input type="password" name="password"/>


<span style="color:red;">*</span>

<br>

<br>

Gender:

<input type="radio"

value="Male"

name="gender"> Male

<input type="radio"

value="Female"

Pr By P Mounika Lecturer in Computer Applications


name="gender">Female

<br>

<br>

<input type="submit" value="Submit" name="submit" />

</form>
</fieldset>

<?php

if(isset($_POST['submit']))

if(!isset($error))

echo"<h1>INPUT RECEIVED</h1><br>";

echo "<table border='1'>";

echo "<thead>";

echo "<th>Parameter</th>";

echo "<th>Value</th>";

echo "</thead>";

echo "<tr>";

echo "<td>First Name</td>";


echo "<td>".$firstname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Last Name</td>";

echo "<td>".$lastname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Address</td>";

echo "<td>".$address."</td>";

Pr By P Mounika Lecturer in Computer Applications


echo "</tr>";

echo "<tr>";

echo "<td>Email Address</td>";

echo "<td>" .$emailaddress."</td>";

echo "</tr>";
echo "<tr>";

echo "<td>Password</td>";

echo "<td>".$password."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Gender</td>";

echo "<td>".$gender."</td>";

echo "</tr>";

echo "</table>";

?>

</body>

</html>

Pr By P Mounika Lecturer in Computer Applications


 Output:

PHP File Upload


With PHP, it is easy to upload files to the server.
Configure The "php.ini" File

First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On

Create The HTML Form

Next, create an HTML form that allow users to choose the image file they want to upload:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>
Some rules to follow for the HTML form above:

Pr By P Mounika Lecturer in Computer Applications


 Make sure that the form uses method="post"

 The form also needs the following attribute: enctype="multipart/form-data". It


specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.

Other things to notice:

 The type="file" attribute of the <input> tag shows the input field as a file-select
control, with a "Browse" button next to the input control

The form above sends data to a file called "upload.php", which we will create next.

Create The Upload File PHP Script


The "upload.php" file contains the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

PHP script explained:

 $target_dir = "uploads/" - specifies the directory where the file is going to be placed

 $target_file specifies the path of the file to be uploaded

 $uploadOk=1 is not used yet (will be used later)

 $imageFileType holds the file extension of the file (in lower case)
 Next, check if the image file is an actual image or a fake image

Pr By P Mounika Lecturer in Computer Applications


Note: You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.

Check if File Already Exists

Now we can add some restrictions.

First, we will check if the file already exists in the "uploads" folder. If it does, an error
message is displayed, and $uploadOk is set to 0:

// Check if file already exists


if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

Limit File Size

The file input field in our HTML form above is named "fileToUpload".

Now, we want to check the size of the file. If the file is larger than 500KB, an error message
is displayed, and $uploadOk is set to 0:

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

Limit File Type

The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file
types gives an error message before setting $uploadOk to 0:

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

Complete Upload File PHP Script


The complete "upload.php" file now looks like this:

Pr By P Mounika Lecturer in Computer Applications


<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image


if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}

// Check if file already exists


if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error


if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

Pr By P Mounika Lecturer in Computer Applications


echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has
been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

PHP Database connection


The collection of related data is called a database. XAMPP stands for cross-platform, Apache,
MySQL, PHP, and Perl. It is among the simple light-weight local servers for website
development.

Requirements: XAMPP web server procedure:

 Start XAMPP server by starting Apache and MySQL.


 Write PHP script for connecting to XAMPP.

 Run it in the local browser.

 Database is successfully created which is based on the PHP code.

In PHP, we can connect to the database using XAMPP web server by using the following
path.

"localhost/phpmyadmin"

Steps in Detail:

Pr By P Mounika Lecturer in Computer Applications


 Open XAMPP and start running Apache, MySQL and FileZilla

 Now open your PHP file and write your PHP code to create database and a table in
your database.

PHP code to create a database:

o PHP

<?php

// Server name must be localhost

$servername = "localhost";

// In my case, user name will be root

$username = "root";

// Password is empty

$password = "";

Pr By P Mounika Lecturer in Computer Applications


// Creating a connection

$conn = new mysqli($servername,

$username, $password);

// Check connection
if ($conn->connect_error) {

die("Connection failure: "

. $conn->connect_error);

// Creating a database named geekdata

$sql = "CREATE DATABASE geekdata";

if ($conn->query($sql) === TRUE) {

echo "Database with name geekdata";

} else {

echo "Error: " . $conn->error;

// Closing connection
$conn->close();

?>

Pr By P Mounika Lecturer in Computer Applications


 Save the file as “data.php” in htdocs folder under XAMPP folder.

 Then open your web browser and type localhost/data.php

Finally the database is created and connected to PHP.

If you want to see your database, just type localhost/phpmyadmin in the web browser and the
database can be found.

Executing an SQL query and fetch results using PHP


We can perform a query against the database using the PHP mysqli_query() method.

Pr By P Mounika Lecturer in Computer Applications


Syntax: We can use the mysqli_query( ) method in two ways:

 Object-oriented style

 Procedural style

Parameters:
 connection: It is required that specifies the connection to use.

 query: It is also required that specifies the database query.

 result mode: It is optional to use.

Return value: For SELECT, SHOW, DESCRIBE, or EXPLAIN it returns a mysqli_result


object. For other successful queries, it returns true. Otherwise, it returns false on failure.

Let’s understand how we can execute an SQL query.

Executing an SQL query: We will understand how we can execute an SQL query with an
example. We will create a database, table and then insert some values into it.

Example: Create a database and insert some values into it.

PHP

<?php

$servername = "localhost";

$username = "root";

$password = "";

$conn = new mysqli($servername, $username, $password);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);


}

$sql = "CREATE DATABASE gfgDB";

if ($conn->query($sql) === TRUE) {

echo "Database has been created successfully";

} else {

Pr By P Mounika Lecturer in Computer Applications


echo "Error creating database: " . $conn->error;

$conn->close();

?>

Output:
Database has been created successfully

Creating the table:

PHP

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "gfgDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);


}

$sql = "CREATE TABLE Emp (

id INT(6) AUTO_INCREMENT PRIMARY KEY,

firstname VARCHAR(30) NOT NULL,

lastname VARCHAR(30) NOT NULL

)";

if ($conn->query($sql) === TRUE) {

echo "Table has been created successfully";

Pr By P Mounika Lecturer in Computer Applications


} else {

echo "Error creating table: " . $conn->error;

$conn->close();
?>

Output:
Table has been created successfully

Inserting some values into the table “Emp”:

PHP

<?php

$servername = "localhost";

$username = "root";
$password = "";

$dbname = "gfgDB";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error){

die("Connection failed: " . $conn->connect_error);

$sql = "INSERT INTO Emp (firstname, lastname)

VALUES ('XYZ', 'ABC')";

if ($conn->query($sql) === TRUE) {

echo "New record created successfully";

}else{

echo "Error: " . $sql . "<br>" . $conn->error;

Pr By P Mounika Lecturer in Computer Applications


}

$conn->close();

?>

Output:
New record created successfully

Note: Since we have used AUTO_INCREMENT, it will automatically insert the record with
“id=1” and for each newly inserted record, it will increase the “id” by one.

Fetching results from the database:

PHP

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "gfgDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "SELECT id, firstname, lastname FROM Emp";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

echo "id: " . $row["id"]. " - Name: "

. $row["firstname"]. " " . $row["lastname"]. "<br>";

Pr By P Mounika Lecturer in Computer Applications


}

else {

echo "No records has been found";

$conn->close();
?>

Output:
id: 1 - Name: XYZ ABC

Handling sessions and cookies


Handling sessions and cookies in PHP is essential for maintaining user state and preferences
across different pages of a web application. Here's a concise guide to help you get started:

Sessions in PHP

Sessions allow you to store user information on the server for later use. This is particularly
useful for maintaining user login states, shopping carts, etc.

Starting a Session:

<?php

session_start(); // Start the session

?>

Setting Session Variables:

<?php
$_SESSION['username'] = 'JohnDoe'; // Set a session variable
?>

Pr By P Mounika Lecturer in Computer Applications


Accessing Session Variables:

<?php

echo $_SESSION['username']; // Access a session variable

?>

Destroying a Session:

<?php

session_start(); // Start the session

session_unset(); // Unset all session variables

session_destroy(); // Destroy the session

?>

Cookies in PHP

Cookies are used to store data on the client's browser, which can be retrieved later. They are
useful for remembering user preferences, tracking user behavior, etc.

Setting a Cookie:

<?php

setcookie('user', 'JohnDoe', time() + (86400 * 30), "/"); // Set a cookie for 30 days

?>

Accessing a Cookie:

<?php
if(isset($_COOKIE['user'])) {

Pr By P Mounika Lecturer in Computer Applications


echo $_COOKIE['user']; // Access the cookie value

?>

Deleting a Cookie:

<?php

setcookie('user', '', time() - 3600, "/"); // Delete the cookie by setting its expiration time in the
past

?>

Combining Sessions and Cookies


You can use both sessions and cookies together to enhance the user experience. For example,
you might use a session to store sensitive information like user IDs and cookies to store non-
sensitive information like user preferences.

<?php

session_start();

$_SESSION['user_id'] = 123; // Store user ID in session

setcookie('theme', 'dark', time() + (86400 * 30), "/"); // Store theme preference in a cookie

// Accessing session and cookie


echo $_SESSION['user_id']; // Output: 123

echo $_COOKIE['theme']; // Output: dark

?>

PHP File Handling


File handling in PHP is used to create, open, read, write, delete, and manipulate files on a
server. It is used when you need to store data persistently or handle files uploaded by
users. PHP provides several built-in functions to make file handling easy and secure.

Pr By P Mounika Lecturer in Computer Applications


Common File Handling Functions in PHP
 fopen() – Opens a file

 fclose() – Closes a file

 fread() – Reads data from a file

 fwrite() – Writes data to a file

 file_exists() – Checks if a file exists

 unlink() – Deletes a file

What is File Handling in PHP?


File handling is the process of interacting with files on the server, such as reading files,
writing to a file, creating new files, or deleting existing ones. File handling is essential for
applications that require the storage and retrieval of data, such as logging systems, user-
generated content, or file uploads.

Opening and Closing Files


Before you can read or write to a file, you need to open it using the fopen() function, which
returns a file pointer resource. Once you’re done working with the file, you should close it
using fclose() to free up resources.

<?php

// Open the file in read mode

$file = fopen("gfg.txt", "r");

if ($file) {

echo "File opened successfully!";

fclose($file); // Close the file

} else {

echo "Failed to open the file.";

?>

File Modes in PHP


Files can be opened in any of the following modes:

Pr By P Mounika Lecturer in Computer Applications


 “w” – Opens a file for writing only. If file does not exist then new file is created and
if file already exists then file will be truncated (contents of file is erased).

 “r” – File is open for reading only.


 “a” – File is open for writing only. File pointer points to end of file. Existing data in
file is preserved.

 “w+” – Opens file for reading and writing both. If file not exist then new file is
created and if file already exists then contents of file is erased.

 “r+” – File is open for reading and writing both.


 “a+” – File is open for write/read. File pointer points to end of file. Existing data in
file is preserved. If file is not there then new file is created.

 “x” – New file is created for write only.

Reading from Files


There are two ways to read the contents of a file in PHP. These are –

1. Reading the Entire File


You can read the entire content of a file using the fread() function or the file_get_contents()
function.

<?php

$file = fopen("gfg.txt", "r");

$content = fread($file, filesize("gfg.txt"));

echo $content;

fclose($file);

?>

2. Reading a File Line by Line


You can use the fgets() function to read a file line by line.
<?php

$file = fopen("gfg.txt", "r");

Pr By P Mounika Lecturer in Computer Applications


if ($file) {

while (($line = fgets($file)) !== false) {

echo $line . "<br>";

fclose($file);

?>

Writing to Files
You can write to files using the fwrite() function. It writes data to an open file in the specified
mode.
<?php

// Open the file in write mode

$file = fopen("gfg.txt", 'w');

if ($file) {

$text = "Hello world\n";


fwrite($file, $text);

fclose($file);

?>

Deleting Files
Use the unlink() function to delete the file in PHP.

<?php

if (file_exists("gfg.txt")) {
unlink("gfg.txt");

Pr By P Mounika Lecturer in Computer Applications


echo "File deleted successfully!";

} else {

echo "File does not exist.";

?>

Appending to a File
Appending to a file is adding new data to the end of an existing file rather than overwriting it.
This is useful for keeping logs, preserving user data and other cases in which previous data
should be stored while new entries are added.

In PHP, the fopen() function returns the file pointer of a file used in different opening modes
such as "w" for write mode, "r" read mode and "r+" or "r+" mode for simultaneous read/write
operation, and "a" mode that stands for append mode.

When a file is opened with "w" mode parameter, it always opens a new file. It means that if
the file already exists, its content will be lost. The subsequent fwrite() function will put the
data at the starting position of the file.

Why Append Data?

Here is the reasons why you need to append data −

 Log Files: When documenting events or problems for a website or application, keep
all prior logs.

 User Submissions: If users submit comments or forms, you may want to save them
as files.

 Data Gathering: You may need to collect data over time while keeping previous
information.

Appending Data to a File in PHP

Assuming that a file "new.txt" is present with the following contents −

Hello World

TutorialsPoint

PHP Tutorial

The following statement −

$fp = fopen("new.txt", "w");


Erases all the existing data before new contents are written.

Pr By P Mounika Lecturer in Computer Applications


Read/Write Mode

Obviously, it is not possible to add new data if the file is opened with "r" mode. However,
"r+" or "w+" mod opens the file in "r/w" mode, but still a fwrite() statement immediately
after opening a file will overwrite the contents.

Example

Take a look at the following code −

<?php
$fp = fopen("new.txt", "r+");

fwrite($fp, "PHP-MySQL Tutorial\n");

fclose($fp);

?>
With this code, the contents of the "new.txt" file will now become −

PHP-MySQL Tutorial
lsPoint

PHP Tutorial

To ensure that the new content is added at the end of the existing file, we need to manually
put the file pointer to the end, before write operation. (The initial file pointer position is at the
0th byte)
The fseek() Function

PHP's fseek() function makes it possible to place the file pointer anywhere you want −

fseek(resource $stream, int $offset, int $whence = SEEK_SET): int

The $whence parameter is from where the offset is counted. Its values are −

 SEEK_SET − Set position equal to offset bytes.

 SEEK_CUR − Set position to current location plus offset.

 SEEK_END − Set position to end-of-file plus offset.

Example

So, we need to move the pointer to the end with the fseek() function as in the following code
which adds the new content to the end.

<?php
$fp = fopen("new.txt", "r+");
fseek($fp, 0, SEEK_END);

Pr By P Mounika Lecturer in Computer Applications


fwrite($fp, "\nPHP-MySQL Tutorial\n");

fclose($fp);

?>
Now check the contents of "new.txt". It will have the following text −

Hello World

TutorialsPoint

PHP Tutorial

PHP-MySQL Tutorial
Append Mode

Instead of manually moving the pointer to the end, the "a" parameter in fopen() function
opens the file in append mode. Each fwrite() statement adds the content at the end of the
existing contents, by automatically moving the pointer to SEEK_END position.

<?php
$fp = fopen("new.txt", "a");

fwrite($fp, "\nPHP-MySQL Tutorial\n");

fclose($fp);

?>
One of the allowed modes for fopen() function is "r+" mode, with which the file performs
read/append operation. To read data from any position, you can place the pointer to the
desired byte by fseek(). But, every fwrite() operation writes new content at the end only.

Example

In the program below, the file is opened in "a+" mode. To read the first line, we shift the file
position to 0the position from beginning. However, the fwrite() statement still adds new
content to the end and doesn't overwrite the following line as it would have if the opening
mode "r+" mode.

<?php
$fp = fopen("new.txt", "a+");

fseek($fp, 0, SEEK_SET);

$data = fread($fp, 12);

echo $data;
fwrite($fp, "PHP-File Handling");

Pr By P Mounika Lecturer in Computer Applications


fclose ($fp);

?>
Thus, we can append data to an existing file if it is opened in "r+/w+" mode or "a/a+" mode

PHP Directory Functions


PHP Directory Introduction

The directory functions allow you to retrieve information about directories and their contents.

Installation

The PHP directory functions are part of the PHP core. No installation is required to use these
functions.

PHP Directory Functions

Function Description

chdir() Changes the current directory

chroot() Changes the root directory

closedir() Closes a directory handle

dir() Returns an instance of the Directory class

getcwd() Returns the current working directory

opendir() Opens a directory handle

readdir() Returns an entry from a directory handle

rewinddir() Resets a directory handle

scandir() Returns an array of files and directories of a specified directory

Pr By P Mounika Lecturer in Computer Applications

You might also like