EasyCoding: PHP File I/O

in #php7 years ago

In this tutorial we will be covering file handling in PHP.


Our code is the following:

Let's break this down!
fopen() is used to open files and make them readable/writeable. It takes two arguments, first the filename, then the mode. There are many different modes, but the most important are these:

  • w: Used to only write to the file, if it already exists the content is deleted.
  • r: Used to only read the file.
  • a: Used to add content after existing content.

fwrite() is used to write files, to use it you need a fopen() with write access assigned to a variable first. It takes two arguments, the fopen() variable first, and the content to be written second.

file_get_contents() is used to read all content of a file into a string. It only needs the name of the file to be read as argument. Here we read the content of “myfile.txt”, which has been written by fwrite before and it gets assigned to the variable $filecontent which we echo afterwards.

After you are done working with a file, you should always use fclose() to close it. Simply give it the variable fopen() was defined to as argument and you’re good to go.


Now, if you did everything correctly and run this code, a file called "myfile.txt"should appear in the directory the script is in. In it there is written" EasyCoding is cool!". Congrats, you just created a file using PHP!
And as always, Happy coding!

Any questions? Leave a comment or send me a message!