PHP File Handling
PHP allows you to read, write, and manipulate files on your server. Here are a few important functions:
Opening a File
To open a file, use the fopen() function:
<?php
$file = fopen("example.txt", "r");
if ($file) {
echo "File opened successfully.";
} else {
echo "Unable to open file.";
}
?>
Reading from a File
To read the contents of a file, use fread():
<?php
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
echo $content;
fclose($file);
?>
Writing to a File
To write to a file, use fwrite():
<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello, this is a test file.");
fclose($file);
?>
Activity
Try It Yourself!
Create a script that opens a file, reads its contents, and writes new data to the file.
Quiz
Quick Quiz
- What function is used to open a file in PHP?
- How do you write to a file in PHP?
Answers: Use fopen() to open a file. Use fwrite() to write to a file.