Creating text files with PHP
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);
- $filename = "testFile.txt";
This is where we define our filename and store it in our variable $Filename - $createfile = fopen($createfile, 'w') or die("can't open file");
The mode 'w' stands for writing to a file, and if the file doesn't exist it will attempt to create it. Createfile will now be our new filehandle. Next time we want to reference to this file we will use the variable Createfile. - fclose($createfile);
Lastly we will close the file before the PHP script ends.
There are a few other modes we can use with the fopen() function.
| r | Open 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. |
| w | Open 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. |
| a | Open 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. |
| x | Create 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 "
