PHP File Handling
PHP File Handling
File handling in PHP is used to you 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.
File handling is the process of interacting with files on the server, such as reading file, 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.
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.
“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.
<?php
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
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
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.";
}
?>
There are two ways to read the contents of a file in PHP. These are –
You can read the entire content of a file using the fread() function or the file_get_contents()
function.
<?php
echo $content;
fclose($file);
?>
You can use the fgets() function to read a file line by line.
<?php
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
if ($file) {
$text = "Hello world\n";
fwrite($file, $text);
fclose($file);
}
?>
Deleting Files
<?php
if (file_exists("gfg.txt")) {
unlink("gfg.txt");
echo "File deleted successfully!";
} else {
echo "File does not exist.";
}
?>
What is a session?
In general, session refers to a frame of communication between two medium. A PHP session is
used to store data on a server rather than the computer of the user. Session identifiers or SID is a
unique number which is used to identify every user in a session based environment. The SID is
used to link the user with his information on the server like posts, emails etc.
Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to easily
modify the content of the cookie. Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user data each
time the user views a page. Every time the browser requests a URL to the server, all the cookie
data for that website is automatically sent to the server within the request.
Starting a PHP Session: The first step is to start up a session. After a session is started,
session variables can be created to store information. The PHP session_start() function is
used to begin a new session.It also creates a new session ID for the user.
<?php
session_start();
?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[]
superglobal array.The stored data can be accessed during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber and
Name:
<?php
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>
Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling
session_start() and then by passing the corresponding key to the $_SESSION
associative array.
The PHP code to access a session data with two session variables Rollnumber and Name
is shown below:
<?php
session_start();
?>
Output:
Destroying Certain Session Data: To delete only a certain session data,the unset feature
can be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative
session array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
?>
<?php
session_start();
session_destroy();
?>
Important Points
PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that the
site can retrieve to personalize the page when the user visits the website next time. A cookie can
only be read from the domain that it has been issued from. Cookies are usually set in an HTTP
header but JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The
setcookie() function needs to be called prior to any output generated by the script otherwise the
cookie will not be set.
Syntax:
Parameters: The setcookie() function requires six arguments in general which are:
Creating Cookies: Creating a cookie named Auction_Item and assigning the value
Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60
seconds).
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
Note: Only the name argument in the setcookie() function is mandatory. To skip an argument,
the argument can be replaced by an empty string(“”).
Output:
Cookie creation in PHP
Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a cookie is
set or not before accessing its value. Therefore to check whether a cookie is set or not, the PHP
isset() function is used. To check whether a cookie “Auction_Item” is set or not, the isset()
function is executed as follows:
Example: This example describes checking whether the cookie is set or not.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Deleting Cookies: The setcookie() function can be used to delete a cookie. For deleting a cookie, the
setcookie() function is called by passing the cookie name and other arguments or empty strings but
however this time, the expiration date is required to be set in the past. To delete a cookie named
“Auction_Item”, the following code can be executed.
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted"
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Important Points:
If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end
of the session i.e. when the browser closes.
The same path, domain, and other arguments should be passed that were used to create
the cookie in order to ensure that the correct cookie is deleted.