Home >> PHP File Handling >> PHP File Create
Creating Files in PHP
In this section we are going to cover creating files using PHP file system function fopen()
Creating file using fopen()
Using the PHP file system function fopen(), we can create a new file. Let's look at this function more closely.
fopen ($filename, $mode);
The function fopen() takes in two arguments, the filename and the mode to either open or create a file.
PHP file fopen create modes
For the list of all modes, please see php site.
Create file
Now let see some examples for creating a new files with fopen for reading and writing.
Example 1 - create new file for writing
<?php $fh = fopen("myfile.txt", "w"); if($fh==false) die("unable to create file"); ?>
The code above creates a new file myfile for writing only in the current directory.
The mode "w" creates a new file for writing, places the pointer in the beginning of the file. If the file already existed, it deletes everything in the file.
What happens when fopen fails?
When you create a file, the function fopen returns a file pointer. If the attempt to create a file fails for any reason, the function returns false.
Example 2 - create file for reading and writing
<?php $fh = fopen(" myfile.txt", "w+"); if($fh==false) die("unable to create file"); ?>
The code above creates a new file as does in example one but it creates the file for both reading and writing in the current directory.
The mode "w+" creates a new file for reading and writing, places the pointer in the beginning of the file. If the file already existed, it deletes everything from the file.
Similarly, you can use mode 'a' and 'a+' for creating new files. However with these modes, if the file already exists, it will not truncate the file (i.e. it will not delete any content in the file) and places the pointer at the end of the file for writing.
So, in the tutorial we learned how to create a new file using the php fopen function, next we will learn how to open existing files for reading and writing using the fopen function.
From HTML to PHP programming... Learn how to build websites in PHP