KEMBAR78
Unit I PHP (BCA) | PDF | Data Type | Php
0% found this document useful (0 votes)
16 views17 pages

Unit I PHP (BCA)

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)
16 views17 pages

Unit I PHP (BCA)

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/ 17

Unit-I

Introduction to PHP:

 PHP Stands for Personal Home Page (earlier called, PHP) is an HTML-embedded, server-sidescripting
language designed for web development.
 It is also used as a general purpose programming language.
 It was created by Rasmus Lerdorf in 1994 and appeared in the market in 1995.
 PHP started out as a small open source project that evolved as more and more people found out.
 Rasmus Lerdorf released the first version of PHP way back in 1994.
 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
 PHP is a server side scripting language that is embedded in HTML. It is used to managedynamic
content, databases, session tracking, even build entire e-commerce sites.
 It is integrated with a number of popular databases, including MySQL, Oracle, Sybase,Informix,
and Microsoft SQL Server.
 The MySQL server, once started, executes even very complex queries with huge resultsets in
record-setting time.
 PHP is forgiving: PHP language tries to be as forgiving as possible.
 PHP Syntax is C-Like.
Uses of PHP:
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and closethem. The other
uses of PHP are:
 PHP can handle forms, i.e. gather data from files, save data to a file, through email you cansend data,
return data to the user.
 You add, delete, and modify elements within your database through PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
Features of PHP:

The main feature of php is open source scripting language so you can free download this and use. PHP isa server side
scripting language. It is widely used all over the world. It is faster than other scripting language. Some important
features of php are given below:

Simple:
It is very simple and easy to use, compare to other scripting language it is very simple and easy, this iswidely used all
over the world.

Interpreted:
It is an interpreted language, i.e. there is no need for compilation.

Open Source:
Open source means you no need to pay for use php, you can free download and use.

Faster: It is faster than other scripting language e.g. asp and jsp.

Platform Independent:
PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.

Case Sensitive:
PHP is case sensitive scripting language at time of variable declaration. In PHP, all keywords (e.g. if, else,while, echo,
etc.), classes, functions, and user-defined functions are NOT case-sensitive.
Advantages of PHP :

 Open source: It is developed and maintained by a large group of PHP developers, this will helpsin creating
a support community, abundant extension library.
 Speed: It is relative fast since it uses much system resource.
 Easy to use: It uses C like syntax, so for those who are familiar with C, it’s very easy for them topick up
and it is very easy to create website scripts.
 Stable: Since it is maintained by many developers, so when bugs are found, it can be quicklyfixed.
 Powerful library support: You can easily find functional modules you need such as PDF, Graphetc.
 Built-in database connection modules: You can connect to database easily using PHP, since many
websites are data/content driven, so we will use database frequently, this will largely reduce the
development time of web apps.
 Platform Independent: It can be run on many platforms, including Windows, Linux and Mac, it’seasy for
users to find hosting service providers.

Disadvantages of PHP:

 Security: Since it is open sourced, so all people can see the source code, if there are bugs in thesource
code, it can be used by people to explore the weakness of PHP.
 Not suitable for large applications: Hard to maintain since it is not very modular.
 Weak type: Implicit conversion may surprise unwary programmers and lead to unexpected bugs. For
example, the strings “1000” and “1e3” compare equal because they are implicitly castto floating point
numbers.

The Basics of PHP scripts:

Let’s jump straight in with a PHP script. To begin, open your favorite text editor. Like HTML documents,PHP files
are made up of plain text. You can create them with any text editor, and most popular HTML editors and
programming IDEs (integrated development environments) provide support for PHP.

Type in the example in Listing 4.1 and save the file to the document root of your web server, using aname something
like first.php.
Listing 4.1: A Simple PHP Script

<?php
echo “<h1>Hello Web!</h1>”;
?>

If you are not working directly on the machine that will be serving your PHP script, you need to use a File Transfer
Protocol (FTP) or Secure Copy (SCP) client to upload your saved document to the server. When the document is in
place on the server, you should be able to access it using your browser. If allhas gone well, you should see the
script’s output.

FIGURE 4.2
Success: the output from
first.php.
Beginning and Ending a Block of PHP Statements:

When writing PHP, you need to inform the PHP engine that you want it to execute your commands. If
you don’t do this, the code you write will be mistaken for HTML and will be output to the browser.
Youcan designate your code as PHP with special tags that mark the beginning and end of PHP code
blocks.

Table 4.1 shows four such PHP delimiter


tags.Table 4.1 PHP Start and End Tags
Tag Style Start Tag End Tag
Standard tags <?php ?>
Short tags <? ?>

ASP tags <% %>


Script tags <script language=”php”> </script>

Adding Comments to PHP Code:


Adding comments to your code as you write can save you time later on and make it easier for
otherprogrammers to work with your code.
A comment is text in a script that is ignored by the PHP engine. Comments can make code
morereadable or annotate a script.

Single-line comments begin with two forward slashes (//)—the preferred style—or a single hash or pound
sign (#). The PHP engine ignores all text between these marks and either the end of the line orthe PHP
close tag:
// this is a comment this is another comment

Multiline comments begin with a forward slash followed by an asterisk (/*) and end with an
asteriskfollowed by a forward slash (*/):
/*
this is a
commentno
ne of this
will be parsed by the PHP engine
*/

PHP Variable:
 The main way to store information in the middle of a PHP program is by using a variable.
 Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand
side andthe expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in
advancewhether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.

 PHP has a total of eight data types which we use to construct


our variables: Integers: are whole numbers, without a decimal
point, like 4195.
Doubles: are floating-point numbers, like 3.14159 or
49.1. Booleans: have only two possible values either true
or false.NULL:
is a special type that only has one value: NULL.
Strings: are sequences of characters, like 'PHP supports string
operations.' Arrays: are named and indexed collections of other
values.
Objects: are instances of programmer-defined classes, which can package up both other kinds ofvalues
and functions that are specific to the class.
Resources: are special variables that hold references to resources external to PHP(such asdatabase
connections).

 The first five are simple types, and the next two (arrays and objects) are compound – the
compound types can package up other arbitrary values of arbitrary type, whereas the
simpletypes cannot.

Superglobal Variables:
In addition to global variables of your own creation, PHP has several predefined variables called
superglobals. These variables are always present, and their values are available to all your scripts.
Each of the following superglobals is actually an array of other variables:
 $_GET contains any variables provided to a script through the GET method.
 $_POST contains any variables provided to a script through the POST method.

 $_COOKIE contains any variables provided to a script through a cookie.

 $_FILES contains any variables provided to a script through file uploads.

 $_SERVER contains information such as headers, file paths, and script locations.

 $_ENV contains any variables provided to a script as part of the server environment.

 $_REQUEST contains any variables provided to a script via GET, POST, or


COOKIE input mechanisms.

 $_SESSION contains any variables that are currently registered in a session.

Accessing Form Variable :


In PHP, form variables are accessed through superglobal arrays, which are automatically populated with data
submitted from an HTML form. The specific superglobal array used depends on the method attribute of the HTML
form:
 $_GET: This array is used when the form's method is set to GET. The form data is appended to the URL
as query parameters.
Code
<form action="process.php" method="get">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
In process.php, you would access the username like this:
Code
<?php
$username = $_GET['username'];
echo "Username: " . $username;
?>
 $_POST: This array is used when the form's method is set to POST. The form data is sent in the body of the
HTTP request and is not visible in the URL.
Code
<form action="process.php" method="post">
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
In process.php, you would access the email like this:
Code
<?php
$email = $_POST['email'];
echo "Email: " . $email;
?>
 $_REQUEST: This array contains data from both $_GET and $_POST, as well as $_COOKIE. While
convenient, it's generally recommended to use $_GET or $_POST specifically for form data to maintain clarity and
avoid potential naming conflicts.
Code
<?php
$value = $_REQUEST['fieldName']; // Accesses data regardless of GET or POST
?>

Variable Handling Functions:


PHP provides a comprehensive set of functions for handling variables, allowing developers to inspect, manipulate,
and manage variable data and types. These functions can be broadly categorized as follows:

Function Description

boolval() Returns the boolean value of a variable

debug_zval_dump() Dumps a string representation of an internal zend value to output

doubleval() Alias of floatval()

empty() Checks whether a variable is empty

floatval() Returns the float value of a variable

get_defined_vars() Returns all defined variables, as an array

get_resource_type() Returns the type of a resource

gettype() Returns the type of a variable

intval() Returns the integer value of a variable

is_array() Checks whether a variable is an array

is_bool() Checks whether a variable is a boolean

is_callable() Checks whether the contents of a variable can be called as a function

is_countable() Checks whether the contents of a variable is a countable value

is_double() Alias of is_float()

is_float() Checks whether a variable is of type float

is_int() Checks whether a variable is of type integer

is_integer() Alias of is_int()

is_iterable() Checks whether the contents of a variable is an iterable value

is_long() Alias of is_int()

is_null() Checks whether a variable is NULL

is_numeric() Checks whether a variable is a number or a numeric string

is_object() Checks whether a variable is an object


is_real() Alias of is_float()

is_resource() Checks whether a variable is a resource

is_scalar() Checks whether a variable is a scalar

is_string() Checks whether a variable is of type string

isset() Checks whether a variable is set (declared and not NULL)

print_r() Prints the information about a variable in a human-readable way

serialize() Converts a storable representation of a value

settype() Converts a variable to a specific type

strval() Returns the string value of a variable

unserialize() Converts serialized data back into actual data

unset() Unsets a variable

var_dump() Dumps information about one or more variables

var_export() Returns structured information (valid PHP code) about a variable

PHP Data Types:


PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be
categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
PHP Data Types: Scalar Types
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
PHP Data Types: Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
PHP Data Types: Special Types
There are 2 special data types in PHP.
1. resource
2. NULL
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often
used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without
fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.
Example:
$dec1 = 34;
$oct1 = 0243;
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or
decimal point, including a negative or positive sign.
$n1 = 19.34;
$n2 = 54.472;

PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters. String values must be enclosed either within single quotes or in double quotes. But both
are treated differently.
$company = "Javatpoint";
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
PHP Constants:

 A constant is a name or an identifier for a simple value. A constant value cannot


change duringthe execution of the script. By default, a constant is case-sensitive.
 constant identifiers are always uppercase. A constant name starts with a letter or
underscore,followed by any number of letters, numbers, or underscores.
 If you have defined a constant, it can never be changed or undefined.
 To define a constant you have to use define () function and to retrieve the value of a
constant,you have to simply specifying its name.
 Unlike with variables, you do not need to have a constant with a $. You can also use the
functionconstant() to read a constant's value if you wish to obtain the constant's name
dynamically.

constant() function:

 As indicated by the name, this function will return the value of the constant. This is useful
whenyou want to retrieve value of a constant, but you do not know its name, i.e., it is stored
in a variable or returned by a function.
constant() example
<?php
define("MIN
SIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Note: Only scalar data (boolean, integer, float and string) can be contained in constants.

Differences between constants and variables:


 There is no need to write a dollar sign ($) before a constant, where as in Variable one
has towrite a dollar sign.
 Constants cannot be defined by simple assignment, they may only be defined using the
define()function.

Valid and invalid constant names:

// Valid constant
names define("ONE",
"first thing");
define("TWO2",
"second thing");
define("THREE_3",
"third thing")

// Invalid constant names define("2TWO", "second thing"); define(" THREE ", "third value");
PHP 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;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable. PHP Operators can be categorized in following forms:
o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
Arithmetic Operators:
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction,
etc. with numeric values.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of

Assignment Operators:
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the left operand.

+= Add then $a += $b Addition same as $a = $a + $b


Assign

-= Subtract then $a -= $b Subtraction same as $a = $a - $b


Assign

*= Multiply then $a *= $b Multiplication same as $a = $a * $b


Assign

/= Divide then $a /= $b Find quotient same as $a = $a / $b


Assign
(quotient)

%= Divide then $a %= Find remainder same as $a = $a % $b


Assign $b
(remainder)

Comparison Operators:
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
Operator Name Example Explanation

== Equal $a == $b Return TRUE if $a is equal to $b

!= Not equal $a != $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b

<= Less than or $a <= $b Return TRUE if $a is less than or equal $b


equal to

>= Greater than $a >= $b Return TRUE if $a is greater than or equal $b


or equal to

Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation

++ Increment ++$a Increment the value of $a by one, then return $a

$a++ Return $a, then increment the value of $a by one

-- decrement --$a Decrement the value of $a by one, then return $a

$a-- Return $a, then decrement the value of $a by one

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.

Operator Name Example Explanation

And And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true

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

Making Decision with Conditions (Or) Flow Control:


 The if, elseif ...else and switch statements are used to take decision based on the differentcondition.
 You can use conditional statements in your code to make your decisions. PHP supports
thefollowing three decision making statements:
 if...else statement - use this statement if you want to execute a set of code
when acondition is true and another if the condition is not true
 elseif statement - is used with the if...else statement to execute a set of code if
one ofseveral condition are true
 switch statement - is used if you want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long blocks
ofif..elseif..else code.

The If...Else Statement:-

 If you want to execute some code if a condition is true and another code if a condition is
false,use the if else statement.

Syntax:
if (condition)
code to be executed if condition
is true;else code to be executed
if condition is false; Example:
 The following example will output "Have a nice weekend!" if the current day is Friday,
otherwiseit will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice
weekend!";else echo
"Have a nice day!";
?>
</body>
</html>

The ElseIf Statement:-

 If you want to execute some code if one of the several conditions is true, then use the
elseifstatement. Syntax:
if (condition)
code to be executed if condition
is true; elseif (condition)
code to be executed if condition
is true;else code to be executed
if condition is false;

Example:
 The following example will output "Have a nice weekend!" if the current day is Friday, and
"Havea nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice
day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice
weekend!"; elseif
($d=="Sun")
echo "Have a nice
Sunday!"; echo
"Have a nice
day!";
?>
</body>
</html>
The Switch Statement:-
 If you want to select one of many blocks of code to be executed, use the Switch statement.
 The switch statement is used to avoid long blocks of
if..elseif..else code. Syntax:
switch (expression)
{
case label1:
code to be executed if expression =
label1;break; case label2:
code to be executed if expression = label2;
break; default:
code to be executed
if expression is
different from
both label1 and
label2;
}
Example:

<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon": echo "Today is
Monday"; break;
case "Tue": echo "Today
is Tuesday"; break;
case "Wed": echo "Today is
Wednesday"; break;
case "Thu": echo "Today is
Thursday"; break;
case "Fri": echo
"Today is Friday"; break;
case "Sat": echo "Today is
Saturday"; break;
case "Sun": echo "Today
is Sunday"; break;
default: echo "invalid day will be entered, try again";
}
?>
</body>
</html>
 It will produce the
following result:
Today is Friday

Repeating Actions Through Iterations (Or) PHP-Loop Types:

 Loops in PHP are used to execute the same block of code a specified number of times.
 PHPsupports following four loop types.
 for - loops through a block of code a specified number of times.
 while - loops through a block of code if and as long as a specified condition is true.
 do...while - loops through a block of code once, and then repeats the loop as long
as aspecial condition is true.
 foreach - loops through a block of code for each element in an array.

The for loop statement:-


 The for statement is used when you know how many times you want to execute a statement
ora block of statements.
Syntax:
for (initialization; condition; increment)
{
code to be executed;
}
The initialize is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is
traditional to name it $i.
Example:
<?php
$n=15;
for($i=1;$i<=10;$
i++)
{
echo "<b>";
//$p=$n*$i;
echo $n." X ".$i." =
".$n*$i."<br>"; echo
"</b>";
}

?>

The while loop statement:-

 The while statement will execute a block of code if and as long as a test expression is
true. If thetest expression is true, then the code block will be executed.
 After the code has executed the test expression will again be evaluated and the loop
willcontinue until the test expression is found to be false.
Syntax:
while (condition)
{
code to be executed;
}
Example:
<?php
$i=1;
//$n=10;
while($i<=5)
{
echo "The
Number=";
echo $i;
echo "<br>";
$i++;//$i=$i+1;
}
?>
The do...while loop statement:-

 The do...while statement will execute a block of code at least once - it will then repeat the
loopas long as a condition is true.
Syntax:
do
{
code to be executed;
}while (condition);

Example:

<?php
$i=10; $n=50; do
{
echo $i;
echo " ";
$i++;
}while($i<=$n);
?>

The foreach loop statement:

 The foreach statement is used to loop through arrays.


 For each pass the value of the current array element is assigned to $value and the array
pointeris moved by one and in the next pass next element will be processed.
Syntax:
foreach (array as value)
{
code to be executed;
}

Example:
<?php
$a = array( 1, 2,
3, 4, 5); foreach(
$a as $value )
{
echo "The Value is $value <br />";
}
?>

Breaking Out of a Control Structure:

In PHP, the primary way to "break out" of a control structure is by using the break statement. This statement is
specifically designed to terminate the execution of the current loop or switch statement and resume execution at
the statement immediately following the terminated structure.
Here's how break functions in different scenarios:
1. Breaking out of Loops (for, foreach, while, do-while):
When break is encountered within a loop, the loop immediately terminates, and the program flow continues with
the code after the loop.
Code
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i is 5
}
echo $i . " "; // This will print 0 1 2 3 4
}
echo "\nLoop ended.";
?>
2. Breaking out of switch statements:
The break statement is crucial within switch statements to prevent "fall-through," where code from
subsequent case blocks would execute if break were omitted.
Code
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "It's Monday!";
break;
case "Tuesday":
echo "It's Tuesday!";
break; // Prevents fall-through to Wednesday
case "Wednesday":
echo "It's Wednesday!";
break;
default:
echo "Unknown day.";
}
?>

Storing and Retrieving Data:

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

Types of File Operations in PHP:


Several types of file operations can be performed in PHP:
 Reading Files: PHP allows you to read data from files either entirely or line by line.
 Writing to Files: You can write data to a file, either overwriting existing content or appending to the end.
 File Metadata: PHP allows you to gather information about files, such as their size, type, and last
modified time.
 File Uploading: PHP can handle file uploads via forms, enabling users to submit files to the server.

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

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:
 "w" – Opens a file for writing only. If the file does not exist, then a new file is created, and if the file
already exists, then the file will be truncated (the contents of the file are erased).
 "r" – File is open for reading only.
 "a" – File is open for writing only. The file pointer points to the end of the file. Existing data in the file is
preserved.
 "w+" – Opens file for reading and writing both. If the file does not exist, then a new file is created, and if
the file already exists, then the contents of the file are erased.
 "r+" – File is open for reading and writing both.
 "a+" – File is open for write/read. The file pointer points to the end of the file. Existing data in the file is
preserved. If the file is not there, then a 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");

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");
echo "File deleted successfully!";
} else {
echo "File does not exist.";
}
?>

Other File Functions:

unction Description

basename() Returns the filename component of a path

chgrp() Changes the file group

chmod() Changes the file mode


chown() Changes the file owner

copy() Copies a file

delete() See unlink()

dirname() Returns the directory name component of a path

disk_free_space() Returns the free space of a filesystem or disk

disk_total_space() Returns the total size of a filesystem or disk

diskfreespace() Alias of disk_free_space()

fclose() Closes an open file

fgetc() Returns a single character from an open file

fgetcsv() Returns a line from an open CSV file

fgets() Returns a line from an open file

file() Reads a file into an array

file_exists() Checks whether or not a file or directory exists

fputs() Alias of fwrite()

fread() Reads from an open file (binary-safe)

fscanf() Parses input from an open file according to a specified format

fseek() Seeks in an open file

fstat() Returns information about an open file

fwrite() Writes to an open file (binary-safe)

glob() Returns an array of filenames / directories matching a specified pattern

is_dir() Checks whether a file is a directory

Locking Files:
File locking in PHP is primarily achieved using the flock() function. This function allows for the implementation of
a simple reader/writer model to manage concurrent access to files, which is crucial in multi-process or multi-user
environments to prevent data corruption.
How to use flock() for file locking:
Open the file: Before locking, the file must be opened using fopen(), which returns a file pointer.
Code
$fp = fopen("path/to/your/file.txt", "w+"); // Open for reading and writing
Acquire the lock: Use flock() with the appropriate lock type.
*LOCK_SH (Shared Lock): Allows multiple processes to read the file concurrently, but prevents exclusive locks
(writing).

*LOCK_EX (Exclusive Lock): Prevents any other process from acquiring a shared or exclusive lock, ideal for
writing.

*LOCK_NB (Non-Blocking): Can be combined with LOCK_SH or LOCK_EX to prevent the flock() call from blocking
if the lock cannot be immediately acquired.
Code
Release the lock: After completing file operations, release the lock using LOCK_UN.
Code
flock($fp, LOCK_UN); // Release the lock
Close the file: Close the file pointer using fclose(). Note that fclose() automatically releases any locks held by
the current process on that file.
Code
fclose($fp);

You might also like