Practically, we use a database to store a relatively larger amount of data on a web server. But sometimes it can be easier and more convenient to directly access files on the storage. Especially when you are dealing with a small amount of data or non-textual data like images, videos, log files, CSV files etc.

In this article, we will learn how to create, access, modify or even delete un-unnecessary files.
This is commonly known as file handling.

Overview of file handeling in PHP

PHP file functions support a wide range of file formats that include: .txt, .log, .csv, .gif, .jpg etc.

Create a file in PHP

First, you may want to know if the particular exist or not, before the creating process. To determine whether a file or directory already exists, you can use the PHP built-in function file_exists.

To find out if the file exists or not, use the following code:

<?php

$file = 'filename.txt';
if(file_exists($file))
  echo "The file $file does exists";
else
  echo "The file $file doesn't exist";
?>

The function file_exists returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

So let’s say, the file doesn’t exist, and we need to create one.  The steps are simple. Open a file with the right mode, write something on it, and close the file.

Wait, I didn’t mention create a file. Well, using PHP built-in function fopen will create the file with the mode entered as an argument.

Fopen() opens file or URL.

<?php 
$file_handle = fopen(“path_to_file\filename.txt”, “r”);
?>

The second parameter specified the type of access you require to the stream. Fopen() will bind the file or URL to the stream. There are eleven modes, but mostly we use only six to handle files.

Mode Description

r Read-only.
r+ Read and Write; Please the file pointer at the beginning of the file
w Write only
w+ Open for reading and write; place the file pointer at the beginning of the file while deleting all of the existing content of the file.
a Write only; place the file pointer at the end of the file.
a+ Read and write; place the file pointer at the end of the file.

Create an empty PHP file and save it as filehandling.php. Type the following code and execute it.

<?php

$file_handle = fopen("filename.txt", "w") or die("Failed to create a file");
$text ="Lets write something on file";
fwrite($file_handle, $text) or die("Could not write anything on file");
fclose($file_handle);
echo "File ".$file_handle. " written successfully";
?>

Code Explanation

Fopen() will create a file if the file doesn’t exist.

fopen(“filename.txt”, “w”) tells the function to open the file for writing only. If you use this function with an existing function, the w mode parameter will delete the old contents even if you didn’t want to delete the old content. To save your file’s content from deletion, use a mode, for appending text to existing text.

Read a file in PHP

The easiest way to read a text file is to get the whole line at once through fgets()

<?php
 $file_handle = fopen("filename.txt", 'r') or
 die("File does not exist or you lack permission to open it");
 $content = fgets($file_handle);
 fclose($fh);
 echo $content;
?>

But what if the file you open to read have more than one line?
Well, file_get_contents() is a PHP built-in function that let you read an entire file without having to use file handles.

<?php
echo file_get_contents("filename.txt");
?>

You can also use the function in as shown below to extract the contents of a file over the internet. For example, the following will extract the content of Google.

<?php

 echo "<pre>"; // Enables display of line feeds
 echo file_get_contents("http://www.google.com");
 echo "</pre>"; // Terminates pre tag

?>

Append a file in PHP

If you open the file with r mode, it will let you write content on the file but the old content will be deleted. To append the text, you can simply open a file with a or a+ mode.

A file pointer is a position inside the file where the next file access will take place.

You can also move the file pointer to the end, and write text on a file. This will work as you are appending the text at the last.

<?php
$file_handle = fopen("filename.txt", 'r+') or die("Failed to open file");
$text = fgets($file_handle);
fseek($file_handle, 0, SEEK_END);
fwrite($file_handle, "$text") or die("Could not write to file");
fclose($file_handle);
echo file_get_contents("filename.txt");
?>

Delete a file in PHP

PHP built-in function unlink() will delete the file being specified from the hard disk.  This action can’t be undone, use with caution.

<?php
$file = "filename.txt";
if (!unlink($file)) echo "Could not delete file";
 else echo "File $file successfully deleted";
?>

With this code, an ugly warning message will be displayed if the file doesn’t exist. To avoid such warning, use file_exists

<?php
$file = "filename.txt";
if(!file_exists($file)) die("No such file exist");
 if (!unlink($file)) echo "Could not delete file";
 else echo "File $file successfully deleted";
?>

Copy file’s content in PHP

If you want to copy one file’s content to another, use the copy function.

<?php
 copy ('namefile.txt', 'namefile2.txt') or die("Could not copy file");
 echo "File successfully copied";
?>

If the file ‘namefile2.txt’ does not exist, it will be created and text will be copied over it.

Related Articles

CRUD Operations in PHP/ MySQL

How to prevent your website from SQL Injection Attacks using PHP?

Remove characters from a string except numbers and letters using PHP

Last modified: February 18, 2019

Comments

Write a Reply or Comment

Your email address will not be published.