Opening a File

Contact Us or call 1-877-932-8228
Opening a File

Opening a File

fopen()

Syntax

fopen (path_to_file, file_mode)

path_to_file can either be a relative or an absolute path.

File Modes
File Mode Description
r open for reading
w open for writing (erases existing content); creates new file if one doesn't exist
a open for appending to end of content; creates new file if one doesn't exist
x create and open for writing (new in PHP 4.3.2); fails and returns false if file already exists
r+ open for reading and writing (erases existing content when file is written to)
w+ open for writing and reading (erases existing content on opening or creates new file if one doesn't exist
a+ open for appending and writing; creates new file if one doesn't exist
x+ create and open for writing and reading (new in PHP 4.3.2); fails and returns false if file already exists

File Permissions

Files that do no have the appropriate permissions settings will fail to open. In this case, the fopen() function will return false and a warning will be given. Use conditional processing as shown below to handle this situation.

$myFile = @fopen('MyFile.txt','a');
if (!$myFile)
{
	echo '<b>Sorry, but the file cannot be opened.</b>';
}
else
{
	// code for processing file
}

The @ symbol in front of first line of code is used to suppress errors. Any errors can then be handled more gracefully.

Next