What PHP functions or methods can be used to read from and write to text files in PHP?
To read from and write to text files in PHP, you can use the `fopen()`, `fread()`, `fwrite()`, and `fclose()` functions. First, you need to open the file using `fopen()` in read or write mode, then you can use `fread()` to read from the file or `fwrite()` to write to the file. Finally, remember to close the file using `fclose()` when you're done.
// Reading from a text file
$file = fopen("example.txt", "r");
if ($file) {
while (!feof($file)) {
$line = fgets($file);
echo $line;
}
fclose($file);
}
// Writing to a text file
$file = fopen("example.txt", "w");
if ($file) {
fwrite($file, "Hello, World!");
fclose($file);
}
Keywords
Related Questions
- What potential security risks are associated with allowing HTML input in PHP forms and how can they be mitigated?
- What are the advantages and disadvantages of storing user upload data in a database table versus individual text files in PHP?
- How can variables be passed invisibly (not through the URL) to the next page in PHP?