How to open and close a file in PHP?

Member

by addison , in category: PHP General , 6 months ago

How to open and close a file in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 6 months 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.