PHP - File Create
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.
- $filename -
the name of the file. This may
also include the absolute path
where you want to create the
file. Example, "/www/myapp/myfile.txt".
- $mode -
mode is used to specify how you
want to create the file. For
example, you can set the mode to
create for read only, or create
a file for read and write. Below
is the list of possible modes
you can use.
PHP file fopen create modes
|
'w' |
Open for writing only; place
the file pointer at the
beginning of the file and
truncate the file to zero
length. If the file does not
exist, it attempt to create
it. |
|
'w+' |
Open for reading and writing;
place the file pointer at the
beginning of the file and
truncate the file to zero
length. If the file does not
exist, attempt to create it. |
|
'a' |
Open for writing only; place
the file pointer at the end of
the file. If the file does not
exist, attempt to create it. |
|
'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. |
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.
|