Creating text files with PHP


You can create, update and delete files with PHP on your own website.
This guide will show you how you can create files using the Fopen() function.

In PHP, a file is created using a command that is also used to open files.
For this we can use the Fopen() function in PHP. The fopen function needs two important
pieces of information to operate. First, we must give it the name of the file that we want
it to open. Secondly, we will tell the function what we plan on doing with that file
We could tell it to read, write or otherwhise from a file.

Since we want to create a file, we must supply a file name and tell PHP that we want to write
to the file. We have to tell PHP we are writing to the file, otherwise it will not create a new file.
$Filename = "testFile.txt";
$CreateFile = fopen($Filename, 'w');
fclose($ourFileHandle);


There are a few other modes we can use with the fopen() function.
rOpen for reading purpose; place the file pointer at the start of the file.
r+Open for reading and writing purposes; place the file pointer at the start of the file.
wOpen for writing purpose; place the file pointer at the start of the file and set the file to NULL length. If the file does not exist, attempt to create a new one.
w+Open for reading and writing purposes; place the file pointer at the start of the file and set the file to NULL length. If the file does not exist, attempt to create a new one.
aOpen for writing purpose; place the file pointer at the end part of the file. If the file does not exist, attempt to create the file.
'a+Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
xCreate and open for writing purpose; place the file pointer at the start of the file.
x+Create and open for reading and writing purposes; place the file pointer at the start of the file.

This concludes the tutorial for creating files with PHP. Keep in mind that the files that you create usualy can be read from the internet.



Posted by James on 2009-06-07 in the category " PHP "