PHP Tutorial
File handling is needed for any application.
PHP has several functions for opening, creating, reading, uploading,editing and closing files.
The PHP fopen() function is used to open a file.
It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode | Description |
---|---|
r |
Opens the file for reading only. It places the file pointer at the beginning of the file. |
r+ |
Opens the file for reading and writing.It places the file pointer at the beginning of the file. |
w |
Opens the file for writing only. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file. |
w+ |
Opens the file for reading and writing only. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file.. |
a |
Opens the file for writing only. It places the file pointer to the end of the file. If file is not found, it creates a new file |
a+ |
Opens the file for reading and writing only.It places the file pointer to the end of the file. If file is not found, it creates a new file. |
The PHP fopen() function is used to open a file.
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
Lets put this into example.
<?php
$myfile = fopen("c:\\folder\\file.txt", "r");
?>
The PHP function is used to close an open file.
fclose($filename);
Lets put this into example.
<?php
$myfile = fopen("c:\\folder\\file.txt", "r");
// some code to be executed....
fclose($myfile);
?>
It's a good programming practice to close all files after you have finished with them.