How to open and close a file in PHP?

Member

by addison , in category: PHP General , 2 years ago

How to open and close a file in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jasen , 2 years ago

@addison 

In PHP, you can open and close a file using the following functions:

  1. fopen(): This function is used to open a file. It takes two arguments, the file name and the mode in which the file should be opened. The mode can be "r" for read-only, "w" for write-only (creates a new file or overwrites an existing one), "a" for append (opens an existing file and moves the pointer to the end of the file), and "x" for exclusive creation (creates a new file but returns an error if the file already exists).


Here is an example of opening a file in read mode:

1
$file = fopen("example.txt", "r");


  1. fclose(): This function is used to close a file. It takes one argument, the file handle returned by the fopen() function.


Here is an example of closing a file:

1
fclose($file);


It is important to always close a file after you are done with it to release the system resources used by the file.

by aniya.jaskolski , a year ago

@addison 

Here is an example of opening a file, reading its contents, and then closing it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$file = fopen("example.txt", "r");

if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line;
    }

    fclose($file);
} else {
    echo "Unable to open file.";
}


And here is an example of opening a file, writing to it, and then closing it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$file = fopen("example.txt", "w");

if ($file) {
    fwrite($file, "This is a test file.
");
    fwrite($file, "Hello, World!");

    fclose($file);
} else {
    echo "Unable to open file.";
}


Note: It's always a good practice to check if the file was successfully opened before performing any operations on it using the fopen() function.