Writing Files
PHP offers multiple appproaches for writing data to files, ranging from low-level file pointer functions to convenient single-call wrappers.
Using fopen(), fwrite(), and fclose()
<?php
$fp = fopen("output.txt", "w") or die("Cannot open file");
$content = "First line of data\n";
fwrite($fp, $content);
$content = "Second line of data\n";
fwrite($fp, $content);
fclose($fp);
?>
The fopen() function requires two paramteers: the target filename and an access mode.
Mode | Description
- --- | --- r | Read-only, starts at the beginning r+ | Read/write, starts at the beginning w | Write-only, truncates file to zero length; creates new file if it doesn't exist w+ | Read/write, truncates file to zero length; creates new file if it doesn't exist a | Append-only, writes to end of file; creates new file if it doesn't exist a+ | Read/append, preserves existing content by writing to end of file x | Write-only, creates new file; returns FALSE if file already exists x+ | Read/write, creates new file; returns FALSE and error if file already exists
If fopen() cannot open the specified file, it returns false.
Using file_put_contents()
This function writes a string to a file in a single operation.
<?php
$filename = 'data.txt';
$newData = "\nAdditional content";
file_put_contents($filename, $newData, FILE_APPEND | LOCK_EX);
?>
The optional flags parameter accepts the following values:
FILE_APPEND- Appends data to existing contentLOCK_EX- Acquires an exclusive lock to prevent concurrent writes
Reading Files
Using file_get_contents()
This reads the entire file contents in to a single string variable.
<?php
$path = 'sample.txt';
if (file_exists($path)) {
$contents = file_get_contents($path);
$processed = str_replace("\r\n", "<br />", $contents);
echo $processed;
}
?>
Using file()
This reads the entire file into an array, where each line becomes a separate array element including line breaks.
<?php
$path = 'sample.txt';
if (file_exists($path)) {
$lines = file($path);
for ($i = 0; $i < count($lines); $i++) {
echo $lines[$i] . "<br />";
}
}
?>