File Operations in PHP – Create, Open, Read, Write and Update


In PHP, you can perform all types of file operations. You can open or create any type of file that you want. You can also read files, write to them or update their content. There are many other things that you can do like forcing a file download while opening it.

For websites, files are used to store data. You can store data in simple txt file. Another great use is to create image files that are dynamic in nature. PHP can open and write down to image files easily. Let us take a look at a few simple file operations.

readfile()

The simplest way to open and output the contents of a file is by using readfile() function.
Example:
You have file.txt which contains:

Note: 35 is the size of file in bytes.

If you try to open images with readfile it will display some unreadable code when executed. You will have to set the header content type as image/jpeg to output it as an image.

The code would be, something like:

Note: We are opening a remote image in this example.

fopen(), fread(), fwrite() and fclose()

These three are usually used to open files, read their contents, or create/write to them. fclose() is used to close the file after the operations are complete.

Here’s how you use them:

The opening mode defines whether files are overwritten or not. We used “r” to read the file, “w” to create a  new file and write to it.

Here are all the modes:

“r” : Open file for reading from the start of the file.
“r+” : Open file for reading and writing from the start of the file.
“w” : Open file for writing from the beginning of the file. If file already exists it is overwritten.
“w+” : Open file for reading and writing; creates a new file if it is not there.
“a” : Open file for writing from the start. Appends to the existing content.
“a+” : Open file for reading and writing at the end. Appends to the existing content.
“x” : Open a new file for writing and error is displayed if file is already present.
“x+”: Open a new file or reading and writing; error is displayed if file is already present.

Other useful functions related to file operations

fgets(): Read a file one line at a time.
fgetc(): Read a file one character at a time.
feof(): To check whether the end of file (EOF) is reached.

For example: A file.txt contains

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers