PHP File
Working with files is an important part of any programming language and PHP is no different. Whatever your reasons are for wanting to manipulate files, PHP will happily accommodate them through the use of a handful of functions.
Fopen() and Fclose()
Fopen() is the basis for file manipulation. It opens a file in a certain mode (which you specify) and returns a handle. Using this handle you can read and/or write to the file, before closing it with the fclose() function.
<?php
$handle = fopen('data.txt', 'r'); // Open the file for reading
fclose($handle); // Close the file
?>
In the example above you can see the file is opened for reading by specifying 'r' as the mode. For a full list of all the modes available to fopen() you can scroll below.
example of using the 'a' mode
<?php
$Handle = fopen('data.txt', 'a'); // Open the file for appending
$Data = "\n\nI am new content.";
fwrite($Handle, $Data);
fclose($Handle);
echo file_get_contents('data.txt');?>
mode parameter
| mode | Description |
|---|---|
| '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 and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. |
| 'x+' | Create and open for reading and writing; otherwise it has the same behavior as 'x'. |
| 'c' | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock() ) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested). |
| 'c+' | Open the file for reading and writing; otherwise it has the same behavior as 'c'. |


