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 File Handling:
- PHP Files Manipulating:
- PHP Readfile() Function:
- PHP File Open – fopen():
- PHP File – fread():
- PHP File – fclose():
- PHP File – Read Single Line:
- Check End Of File – feof():
- PHP File – Read Single Character:
- PHP File Write:
- PHP Write File – fwrite():
- PHP Create File – fopen():
- PHP File Update/Overwrite:
- PHP File Upload:
- Configure PHP.ini File:
- Create HTML Form:
- PHP Files Upload Script:
- Check if File Already Exists:
- PHP Files Size Limit:
- PHP Files Type Limit:
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.
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:
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):
We can read files from different file locations into the computer using the readfile() function:
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.
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:
There are a number of ways in which you can open the file, including:
|r||Read-only file. Initially, the file pointer is placed at the beginning.|
|w||Write-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.|
|a||Write-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|
|x||Write 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:
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:
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:
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:
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.
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:
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:
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:
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:
PHP Files Upload Script
The following is an explanation of the PHP script:
- $dir = “uploads/” – specifies the location of where the file is going to be uploaded.
- The $file parameter specifies the location of the file that will be uploaded.
- $upload_status = 1 is not yet used (it will be used in the future).
- $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.
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:
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:
PHP Files Type Limit
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.
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.