File handling in PHP
To simply get the contents of a file and store it as a string, use the
This code will simply output the contents of the file. Alternatively you can get the contents of a file line by line in an array using the
foreach(file('hello.txt') as $text) echo $text.'<br />';
The lines of the file are returned as an array and this code outputs each line.
To write data to a file you have to open the file, and then use the
fwrite function to write data to the file. The
fopen function accepts two arguments, a file pointer and a method of opening the file, the various methods are outlined below.
|Read only from beginning of file||r|
|Read and write from beginning of file||r+|
|Write only (overwrite)*||w|
|Read and write (overwrite)*||w+|
|Write only (append)*||a|
|Read and write (append)*||a+|
|Create and open a file for writing (if the file exists false will be returned)*||x|
|Create and open a file for reading and writing (if the file exists false will be returned)*||x+|
* If the file does not exist then one will be created.
$open = fopen('hello.txt','w+'); $text = 'Hello'; fwrite($open, $text); fclose($open);
This example opens a file and overwrites the contents with a string. An alternative is to use
file_put_contents('hello.txt', 'my string');
This writes the data to the file specified (and creates the file if it does not exist). This function automatically overwrites data but can be set to append data.
file_put_contents('hello.txt', 'my string', FILE_APPEND);
PHP has a variety of methods for working with files. The examples below demonstrate simple uses of them.
These functions return the size of the file specified and the type of the file (dir, file etc).
is_readable($file); is_writable($file); file_exists($file);
These functions check whether a file is readable, writable or exists respectively.
copy($file); rename($oldFile, $newFile); unlink($file);
This set of functions can copy a file, rename a file or delete a file respectively.