PHP File Handling

PHP file handling module provides you with the ability to create, read, write, and delete files on a server with a variety of attachments.

It is essential to use this feature when building web applications that need to store or manipulate data on files.

The goal here is to provide you a clear understanding of PHP file handling in your web application to manage files in the most efficient and effective way.



PHP Files Manipulating

You can create, read, upload, edit, and modify files in PHP using a number of functions.

Manipulate files carefully!

You must be very careful when manipulating files.

A mistake can cause a lot of damage.

The most common errors are:

  • Editing the wrong file.
  • Creating a HDD full of garbage data.
  • Accidentally deleting the content of a file by mistake.

PHP Readfile() Function

Readfile() is a function used to read files from the input buffer and write them to the output buffer.

Let us assume that we have a text file called acronym.txt stored on the server, which has the following contents:

PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
HTML = HyperText Markup Language
CSS = Cascading Style Sheets
JS = JavaScript
JSON = JavaScript Object Notation
AJAX = Asynchronous JavaScript and XML
ASP = Active Server Page
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

Below PHP code is used to read the file from the disk and write it to the buffer (the readfile() function returns the value of how many bytes were read upon success):

Example: 

<?php echo readfile("acronym.txt"); ?>

We can read files from different file locations into the computer using the readfile() function:

Example: 

<?php echo readfile("/downloads/data/acronym.txt"); ?>

Example Explanation

Above example reads the contents of a file called acronym.txt located in the /downloads/data/ directory on the server using the readfile() function.

  • The readfile() function is a built-in PHP function that reads the contents of a file and outputs it to the browser directly without storing it in a variable. In this case, the contents of the file “acronym.txt” will be output directly to the browser as text.
  • The readfile() function takes a single parameter, which is the path to the file to be read. In this case, the path is “/downloads/data/acronym.txt“. The path is relative to the root directory of the server, which means that the file is located in a directory called “downloads” within a directory called “data“.
  • The echo statement is used to output the contents of the file to the browser. The readfile() function returns the number of bytes read from the file, which is not important in this case since we are only interested in outputting the contents of the file to the browser.
The output of this code will be the contents of the “acronym.txt” file located at the specified path.

Using readfile() is useful if all you need to do is read the contents of a file.


PHP File Open – fopen()

If you want to open a file using a better method, you can use the fopen() function.

You will get more options with this function than you will get with the readfile() function.

During this lesson, we will be open a text file known as acronym.txt which we created above.

fopen() has two parameters, the first of which specifies the name of the file that is to be opened and the second of which identifies the mode in which the file is to be opened.

As shown in the below example, a message is also displayed if the fopen() function is not able to open the specified file, indicating the error:

Example: 

<?php $file = fopen("acronym.txt", "r") or die("The file could not be opened!"); echo fread($file,filesize("acronym.txt")); fclose($file); ?>
Hint: You will be able to learn about the functions fread() and fclose() in the following section.

There are a number of ways in which you can open the file, including:

ModesOverview
rRead-only file. Initially, the file pointer is placed at the beginning.
wWrite-only file. Creates a new file if it does not exist, or erases the contents of the existing file if it does not exist. Initially, the file pointer is placed at the beginning.
aWrite-only file. Data in the file is preserved. Initially, the file pointer is placed at the end. If the file does not exist, then create another one
xWrite only to a new file. The return value is FALSE and an error will be thrown if the file already exists
r+Read / Write file. Initially, the file pointer is placed at the beginning.
w+Read / Write file. Creates a new file if it does not exist, or erases the contents of the existing file if it does not exist. Initially, the file pointer is placed at the beginning.
a+Read / Write file. Data in the file is preserved. Initially, the file pointer is placed at the end. If the file does not exist, then create another one
x+Read / Write to a new file. Data in the file is preserved. Initially, the file pointer is placed at the end. If the file does not exist, then create another one

PHP File – fread()

When fread() is called, it reads the contents of a file that is already open.

PHP fread() takes two parameters, the first of which is the name of the file that is supposed to be read from, and the second of which specifies how many bytes will be read at once.

Here is the PHP code that reads the entire contents of a file acronym.txt as follows:

fread($file,filesize(“acronym.txt”));

PHP File – fclose()

In order to close an opened file, we use the fclose() function.

Whenever you have finished working on a file, it is good programming practice to close it.

You do not want an open file taking up space on your server and taking up resources while it is running around.

To use the fclose() method, we need to pass it the name of the file that we are trying to close (or a variable that holds the filename):

<?php
$file = fopen(“acronym.txt”, “r”);
// There is a code that needs to be executed….
fclose($file);
?>

PHP File – Read Single Line

Fgets() is a function that reads one line of a file at a time from the disk.

Here is an example output of the first line of the acronym.txt file that follows:

Example: 

<?php $file = fopen("acronym.txt", "r") or die("The file could not be opened!"); echo fgets($file); fclose($file); ?>
Remember: The file pointer has been moved to the next line after a call to the fgets() function.

Check End Of File – feof()

A feof() function is used to check if a file has reached the end of the file (EOF).

Using the feof() function allows you to loop through data that is unknown in length in an efficient manner.

Here is an example of reading the acronym.txt file line by line, until the end of the file is reached:

Example: 

<?php $file = fopen("acronym.txt", "r") or die("The file could not be opened!");// Until file ends, output one line while(!feof($file)) { echo fgets($file) . "<br>"; } fclose($file); ?>

PHP File – Read Single Character

We use the fgetc() function when we want to read a single character from a file.

Here is an example of how the acronym.txt file is read character by character until it reaches the end of the file:

Example: 

<?php $file = fopen("acronym.txt", "r") or die("The file could not be opened!");// Until file ends, output one character while(!feof($file)) { echo fgetc($file); } fclose($file); ?>

Example Explanation

Above example reads the contents of a file called acronym.txt using the fopen() function.

  • The fopen() function returns a file handle, which is stored in the $file variable – If file cannot be opened, the die() function is called, which outputs an error message to the browser and terminates the script.
  • The “r” parameter passed to the fopen() function specifies that the file should be opened in read-only mode.
  • The while loop is used to read the file character by character until the end of the file is reached.
  • The feof() function is used to determine whether the end of the file has been reached.
  • The fgetc() function is used to read one character from the file handle, and the echo statement outputs the character to the browser.
  • Finally, the fclose() function is used to close the file handle.
Remember: When the fgetc() function is called, the file pointer is moved to the next character in the file.

PHP File Write

In this section of article, we are going to create PHP file and write data to it.

We will look at some of the different functions and parameters that are used when creating and writing data to PHP files.

The first thing you should check when attempting to run this code is that your PHP file has been granted access to write information to a hard drive.


PHP Write File – fwrite()

To write to a file, you can use the fwrite() function in your program.

fwrite() accepts two parameters.

  • The first one contains the name of the file to be written to.
  • the second one contains the string to be written to.

The following example creates a new file named names.txt with the names of a couple of people:

Example: 

<?php $file = fopen("names.txt", "w") or die("The file could not be opened!"); $text = "Bill Gates"; fwrite($file, $text); $text = "Jeff Bezos"; fwrite($file, $text); fclose($file); ?>

The file names.txt has been written to twice during this process. We sent the string $txt every time we attempted to write to the file, which first contained the string “Bill Gates” and then the string “Jeff Bezos“.

As soon as we had finished writing, we used the fclose() function to close the file.

Here is what the names.txt file looks like if we open it:

Bill Gates
Jeff Bezos

PHP Create File – fopen()

PHP file fopen() is used to create a new file – It may seem confusing to you, but in PHP it is possible to create a file by using the same function used to open it.

When you use fopen() to open a file that does not exist, if the file is being opened for writing (w) or appending (a), it will create the file for you.

Here is an example of how to create a new file called newfile.txt by following the instructions below.

It will be created in the same directory where the PHP code is located and will be named as follows:

Example: 

<?php $file = fopen("newfile.txt", "w"); ?>

PHP File Update/Overwrite

Since names.txt contains some data, it can be shown what happens when a file is opened for access to writing while we are already writing other data into it.

The data in the existing file will be wiped out and a new file will be created starting from scratch.

We are going to open our existing file names.txt, and we are going to write some data into it as follows:

Example: 

<?php $file = fopen("names.txt", "w") or die("The file could not be opened!"); $text = "Bernard Arnault"; fwrite($file, $text); $text = "Elon Musk"; fwrite($file, $text); fclose($file); ?>

Now, if we were to open the names.txt file, both Bill Gates and Jeff Bezos would be gone, and only the data we had just written would remain:

Bernard Arnault
Elon Musk

PHP File Upload

Uploading files has become an integral part of many web applications in today’s digital age, allowing users to share, store, and access files over the internet.

In this section, you’ll learn how to create efficient and secure PHP file upload systems, whether you’re new to PHP or an experienced developer.

We’ll examining how to create an HTML form for input of files, how to process the files on the server-side, and how to validate and secure the files once they’re uploaded.


Configure PHP.ini File

The first thing you should do is make sure that PHP is configured to allow file uploads.

The file_uploads directive can be found in your php.ini file. Make sure that it is set to On.

file_uploads = On

Create HTML Form

For the HTML form there are a few rules that need to be followed:

  • The method should be set to post in the form.
  • It is also necessary to include the following attribute in the form: enctype=”multipart/form-data”. Specifies what type of content should be used when submitting the form.
  • If you do not meet the requirements above, you will not be able to upload files.
  • Input fields with type=”file” attributes display as file-select controls with a “Browse” button next to them.
  • We are sending data to a file called imageUpload.php, which we will create in the next step.

Now, you will need to create an HTML form that will allow the visitors to select the image file they would like to upload.

Below is example code:

Example: 

<!DOCTYPE html> <html><body> <form action="imageUpload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="imageToUpload" id="imageToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body></html>

PHP Files Upload Script

File imageUpload.php contains the code that will be used for uploading a file to the server:

Example: 

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

The following is an explanation of the PHP script:

  1. $dir = “uploads/” – specifies the location of where the file is going to be uploaded.
  2. The $file parameter specifies the location of the file that will be uploaded.
  3. $upload_status = 1 is not yet used (it will be used in the future).
  4. $imgFileType consists of a string that holds the file extension of the image (in lowercase).

The next thing you should do is to determine if the picture file is an actual image or if it is a fake picture.

Remember: In order to do this, you will need to create a directory called “uploads” within the directory in which the “imageUpload.php” file is located. There will be a folder in which you can save the files that you upload.

Check if File Already Exists

We can now add some restrictions.

Our first step will be to check whether the file already exists in the “uploads” folder of the server.

If it does, an error message will be displayed, and the value of $upload_status will be set to 0 as a result:

Example: 

// Check if file already exists if (file_exists($file)) { echo "File already exists."; $upload_status = 0; }

PHP Files Size Limit

In the HTML form above, there is a field named imageToUpload that allows visitors to upload files.

The next thing we want to do is check the size of the file.

An error message will displayed if the file size exceeds 500KB, and a status of 0 is set to the upload_status if the file size exceeds 500KB:

Example: 

// Check file size if ($_FILES["imageToUpload"]["size"] > 500000) { echo "File size must be up to 500KB"; $upload_status = 0; }

PHP Files Type Limit

In the code below, visitors will only be able to upload JPG, JPEG, PNG, and GIF files.
The error message will be shown before setting $upload_status to 0 for all other types of files:

Example: 

// Allow certain file formats if($imgFileType != "jpg" && $imgFileType != "png" && $imgFileType != "jpeg" && $imgFileType != "gif" ) { echo "Only JPG, JPEG, PNG & GIF files are allowed!"; $upload_status = 0; }
Here is the complete “imageUpload.php” file, which now looks like this:

Example: 

<?php $dir = "uploads/"; $file = $dir . basename($_FILES["imageToUpload"]["name"]); $upload_status = 1; $imgFileType = strtolower(pathinfo($file, PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["imageToUpload"]["tmp_name"]); if ($check !== false) { echo "File is an image – " . $check["mime"] . "."; $upload_status = 1; } else { echo "This file is not an image."; $upload_status = 0; } } // Check if file already exists if (file_exists($file)) { echo "File already exists."; $upload_status = 0; } // Check file size if ($_FILES["imgFileType"]["size"] > 500000) { echo "File size must be up to 500KB"; $upload_status = 0; } // Allow certain file formats if ($imgFileType != "jpg" & $imgFileType != "png" && $imgFileType != "jpeg" && $imgFileType != "gif") { echo "Only JPG, JPEG, PNG & GIF files are allowed!"; $upload_status = 0; } // Check if $upload_status is set to 0 by an error if ($upload_status == 0) { echo "Your file was not uploaded."; // if everything is ok, try to upload file} else { if (move_uploaded_file($_FILES["imgFileType"]["tmp_name"], $target_file)) { echo "The file " . htmlspecialchars(basename($_FILES["imgFileType"]["name"])) . " has been uploaded."; } else { echo "There was an error uploading your file."; } }

Example Explanation

In above example first we have set the directory where the uploaded file will be stored and constructs the file path by concatenating the directory path and the basename of the uploaded file.

Then, the script checks if the submitted form has a “submit” button and if the uploaded file is an actual image by calling the “getimagesize()” function on the temporary file name.

If the file is an image, the MIME type is echoed to the user, and the “upload_status” variable is set to 1. Otherwise, an error message is displayed, and the “upload_status” variable is set to 0.

Next, the script checks if the file already exists in the target directory. If it does, an error message is displayed, and the “upload_status” variable is set to 0.

The script also checks if the file size is greater than 500KB and only allows certain file formats (JPG, JPEG, PNG, and GIF) to be uploaded.

If the file size or format is invalid, an error message is displayed, and the “upload_status” variable is set to 0.

Finally, we check if the upload_status variable is set to 0 by an error. If it is, an error message is displayed. If everything is okay, the script attempts to move the uploaded file to the target directory using the move_uploaded_file() function.

If the file is moved successfully, a success message is displayed, and if not, an error message is displayed.
We value your feedback.
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *