PHP File Open

The PHP File Open method and modes will be covered in this chapter.

PHP File Open – fopen()

The fopen() function is a better way to open files. In comparison to readfile(), this function provides more options.

Syntax:

resource fopen ( $file, $mode, $include_path, $context)

Parameters of fopen():

In PHP, the fopen() method takes four parameters.

ParameterData TypeDescription
$file Parameter data type is StringThis is a required argument that specifies the file.
$modeParameter data type is StringIt is a required parameter that indicates the file or stream’s access type.
$include_pathParameter data type is boolIt is an optional parameter that is set to 1 if you prefer to look for the file in the include path.
$contextParameter data type is resourceIt’s an optional parameter for controlling the stream’s behavior.

File Modes:

Now that we have demonstrated that $mode is a mandatory parameter that specifies the file or stream’s access type, let’s have a look at the various mode values.

One of the following modes can be used to open the file:

ModesDescription
rIt is for “Read Only.” The file pointer begins at the start of the file.
wIt is for “Write Only.” It opens a file and clears its contents, or creates a new file if it does not exist. The file pointer begins at the start of the file.
aIt is for “Write Only.” The data in the file is preserved. The file pointer begins at the file’s end. If the file does not exist, it is created.
xIt is for “Write Only.” It creates a new file and returns FALSE if the file already exists, as well as an error if the file already exists.
r+It is for “Read/Write.” The file pointer begins at the start of the file.
w+It is for “Read/Write.” It opens a file and clears its contents, or creates a new file if it does not exist. The file pointer begins at the start of the file.
a+It is for “Read/Write.” The data in the file is preserved. The file pointer begins at the file’s end. If the file does not exist, it is created.
x+It is for “Read/Write.” It creates a new file and returns FALSE if the file already exists, as well as an error if the file already exists.

Let’s take a look at the file we want to open, and then we will see an example of how to open it.

The text file “languages.txt” will be used.

HTML HyperText Markup Language 
CSS  Cascading Style Sheet 
PHP PHP Hypertext Preprocessor 
SQL  Structured Query Language 
<!DOCTYPE html>
<html>
<body>

<?php
$file = fopen("languages.txt", "r") or die("Unable to open file!");
?>

</body>
</html>
PHP File Open

We’ll look at how to read data from a file in the next chapter.