PHP FILE Handling
PHP FILE Handling
• The readfile() function reads a file and writes it to the output buffer.
• Assume we have a text file called "webdictionary.txt", stored on the server, that looks like
this:
• The first parameter of fopen() contains the name of the file to be opened and
the second parameter specifies in which mode the file should be opened. The
following example also generates a message if the fopen() function is unable
to open the specified file:
PHP Open File - fopen()Example
PHP Read File - fread()
• The feof() function is useful for looping through data of unknown length.
• The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
PHP Read Single Character - fgetc()
• The example below reads the "webdictionary.txt" file character by character, until end-
of-file is reached:
PHP File Create/Write
• PHP Create File - fopen()
• The fopen() function is also used to create a file. Maybe a little confusing, but in PHP,
a file is created using the same function used to open files.
• If you use fopen() on a file that does not exist, it will create it, given that the file is
opened for writing (w) or appending (a).
• The example below creates a new file called "testfile.txt". The file will be created in
the same directory where the PHP code resides:
PHP Write to File - fwrite()
• The first parameter of fwrite() contains the name of the file to write to and the
second parameter is the string to be written.
• The example below writes a couple of names into a new file called "newfile.txt":