Tuesday, February 16, 2010

Creating Files Using PHP

When working with files, PHP has several useful functions such as fopen(),fread(), fwrite() and fclose(). Fopen() opens a file or url and the sytax is fopen(string $filename, string $mode). If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Here is a simple PHP script that opens an existing text file, creates and writes to a new file and then closes the file.
?php
//create and open a new file
$newfile = fopen("c:\\xampp\\htdocs\\philduhe.txt", "a+");
fwrite($newfile, "This is Phil's new file.");
fclose($newfile);
echo "All done!";
?>
The mode parameter specifies the type of access or stream to the file. It may be any of the following listed below. In my script, I used the mode of +a to read and write to to the file.
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'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, 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.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE. If the file does not exist, attempt to create it.
'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail. If the file does not exist, attempt to create it.
On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

No comments:

Post a Comment

Get your own Widget