PhpMyanmar.com logo Php Tutorial
Home
Php Tutorial
 Echo
 If

File Open
Show Myanmar Version
 show-myanmar-font
Printer Friendly Page

In this lesson we will be going into the details of fopen function.

Different Ways to Open a File

PHP requires you to specify your intentions when you open a file.

Below are the three basic ways to open a file.

  • Read: 'r'

Open a file for read only use. The file pointer begins at the front of the file.

  • Write: 'w'

Open a file for write only use. In addition, the data in the file is erased as the file open.

You will begin writing data at the beginning of the file. This is also called truncating a file.

The file pointer begins at the start of the file.

  • Append: 'a'

Open a file for write only use but the data in the file is preserved.

You begin will writing data at the end of the file.

The file pointer begins at the end of the file.

A file pointer

A file pointer is the way of remembering a location in a file.

When you open a file for reading, the file pointer begins at the start of the file.

When you open a file for appending, the file pointer is at the end of the file so that you can add (append) data at the end of the file.

When you use reading or writing functions they begin at the location specified by the file pointer.

File Open: Advanced

There are additional ways to open a file.

Above we stated the standard ways to open a file.

You can open a file in such a way that reading and writing is allowable!

This combination is done by placing a plus sign "+" after the file mode (option) character.

  • Read/Write: 'r+'

Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.

  • Write/Read: 'w+'

This is exactly the same as r+, except that it deletes all information in the file when the file is opened.

  • Append: 'a+'

This is exactly the same as r+, except that the file pointer is at the end of the file.

File Open: Cookie Cutter

Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).

Pseudo PHP Code:
$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);

Note For more detail please see Php Manual at http://www.php.net

Processing time -- 0.0532 seconds.

e210a6ace764eb4148c4fd6c3e3e3c2c