Friday, June 26, 2020

How to Create, Write, Read, and Delete Files in PHP

How to Create, Write, Read, and Delete Files in PHP

In this tutorial, we are going to learn file handling in PHP. I'll show you how to create, read, write, and delete files in PHP by using the built-in file handling functions.

File handling is something that you will need to do very often as a PHP developer.

You could use PHP file handling functions to manipulate files in different ways. These functions could be used to build features in your applications that range from custom error logging to storing cached files. Examples of utility tools that you could build with these functions are:

  • custom logging and debugging tools
  • application configuration storage
  • front-end and application caching
  • localization support
  • and many more

PHP provides several file handling functions that allow you to perform various operations, like:

  • create and open a file
  • write into a file
  • read from a file
  • delete a file
  • close a file

Today, we’ll go through each and every file operation, along with examples of how to use them. I would encourage you to try out the examples in this tutorial as you follow along, so that you can actually learn and understand how they work. And if something doesn’t work as expected for you, feel free to post your queries by using the feed at the end of this tutorial.

How to Create and Open a File

In this section, we’ll see how to create and open a file.

When it comes to creating a file, it’s the fopen function which you'll end up using most of the time. It may seem a bit confusing to use the fopen function to create a file. In fact, the fopen function does two things: it creates a file if it doesn't exist and also opens it for reading or writing.

Let’s go through the following example to understand how it works.

In the above example, the fopen function will check if the /home/tutsplus/files/tmp.txt file exists, and if it exists, it’ll open it for writing. By supplying 'w' in the second argument, we specify that we will be writing to the file. If the file doesn’t exist, it’ll be created right away. It’s important to note here that the /home/tutsplus/files/ directory in the above example must be writable by the web server user for the fopen function to be able to create a file.

The first argument of the fopen function is the filename which you want to open. In the above example, we’ve supplied the /home/tutsplus/files/tmp.txt filename in the first argument. Again, it’s important to note that we’ve supplied an absolute path name.

The second argument is the mode, which specifies the type of access you require to the opened file. The fopen function provides different modes you can choose from. For example:

  • use the r mode to open a file for reading
  • the r+ mode for both reading and writing
  • a mode for reading and appending

In our example, we’ve used the w mode, which opens the /home/tutsplus/files/tmp.txt file for writing only. Feel free to go through the official documentation to see different modes supported by the fopen function.

fopen returns a file system pointer, which is used for the other file functions like reading and writing.

How Can I Open Remote Files?

The fopen function isn't just for local files. It also supports other protocols and can open files from elsewhere on your network or the web. If you’ve enabled the allow_url_fopen directive in PHP, you could open remote files as well.

It’s really important to note that when you enable the allow_url_fopen directive, you are creating some security risks, since it opens the door for remote file execution and other attacks. So make sure you take extra security measures in your application if you’re going to enable this directive.

How to Write to a File With PHP

There are a couple of different ways you can write to a file with PHP.

The fwrite Function

First and foremost is the fwrite function, which allows you to write string contents to the file stream referenced by the file handle. Let’s go through the following example to understand how it works.

First, we’ve opened the /home/tutsplus/files/tmp.txt file with the a+ mode, which opens it for reading and writing, with the file pointer placed at the end of the file. Thus, our content will be appended to the end of the file, after any other contents. Next, we’ve used the fwrite function to write a string. 

The first argument of the fwrite function is the file system pointer returned by fopen—this is how fwrite knows where to write into. And the second argument is a string which we want to write into a file. As you can see in the above example, you can use the fwrite function multiple times to write a series of strings before you close the file.

Finally, we’ve used the fclose function to close the file. It takes only one argument, the file pointer that you want to close. It’s always a good practice to close files by using the fclose function once you’ve finished with your file operations.

The file_put_contents Function: A PHP Shortcut for Writing to Files

In the previous section, we discussed the fwrite function, which is used to write into a file. You would have noticed that, if you want to write into a file, you need to open it with the fopen function in the first place. After that, you need to use the fwrite function to write your data into a file, and finally you need to use the fclose function to close the file.

If that sounds too much to you, there’s a shortcut: file_put_contents. The file_put_contents function allows you to write data to a file in a single call.

Let’s see how it works.

The first argument of the file_put_contents function is a filename, and the second argument is a string which you want to write into a file. If the file doesn’t exist, it’ll be created.

As you can see, the file_put_contents function is a shortcut when you just want to write a piece of data to a file.

How to Read From a File in PHP

Now you know how to create and write into a file. In this section, I'll show you how to read from a file.

The fread Function

The fread function allows you to read from a file. It's similar to fwrite, but you need to provide the length in bytes you want to read.

Let’s have a look at the following example to understand how it works.

As we want to read from the /home/tutsplus/files/tmp.txt file, we’ve opened it with the r mode. Next, we’ve used the fread function to read all the contents of the file into the $content variable.

The first argument of the fread function is the file system pointer, so that it knows where to read from. The second argument is the length in bytes you want to read from a file. In our case, we want to read all the contents of the /home/tutsplus/files/tmp.txt file, and thus we’ve used the filesize function to measure the size of the file.

The file_get_contents Function: A PHP Shortcut for Reading From Files

In the previous section, we discussed the fread function, which allows you to read a file by specifying the length in bytes you want to read. If you want to read an entire file at once, there's a function which allows you to do just that: file_get_contents.

Let’s see the file_get_contents function in action!

As you can see, it’s pretty straightforward to use the file_get_contents function—just provide a filename in the first argument.

How to Delete a File in PHP

In this last section, we’ll see how you can delete files. To delete a file in PHP, use the unlink function. Let’s go through an example to see how it works.

The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE, depending on whether the delete operation was successful.

Conclusion

In this post, we discussed the basics of file handling in PHP. Throughout the article, we discussed different operations you can perform by using file functions in PHP. If you have any queries or suggestions, feel free to post them using the feed below!

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

 

In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.



No comments:

Post a Comment