What is the purpose of the fopen function in PHP and how is it typically used?
The fopen function in PHP is used to open a file or URL and return a file pointer resource that can be used for reading, writing, or appending data to the file. It is typically used to read from or write to files on the server or on external resources. The function allows for various modes of file access, such as reading, writing, appending, and creating new files.
// Example of using fopen to read from a file
$filename = "example.txt";
$handle = fopen($filename, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
} else {
echo "Error opening the file.";
}