PHP provides functions to open, read, write, and close files. You can use these functions to interact with files on the server.
To open a file, use the fopen()
function:
<?php
$file = fopen("example.txt", "r"); // Opens the file in read mode
if ($file) {
echo "File opened successfully!";
}
?>
To read a file, use fgets()
or fread()
:
<?php
$file = fopen("example.txt", "r");
while ($line = fgets($file)) {
echo $line;
}
fclose($file);
?>
To write to a file, use fwrite()
:
<?php
$file = fopen("example.txt", "w");
fwrite($file, "This is some new text.");
fclose($file);
?>
Create a script that writes your name to a file called "name.txt" and then reads it back to you.
Answers: You use fopen()
to open a file. To read it line by line, use fgets()
.