Monday, December 22, 2025
HomeLanguagesWhat is the difference between fopen() and fclose() functions in PHP ?

What is the difference between fopen() and fclose() functions in PHP ?

In this article, we are going to discuss the differences between fopen() and fclose() functions.

fopen() function: This function helps users to open a file or a web URL. It mainly accepts two parameters – One is $file that specifies the file or an URL to be opened and the other is $mode that specifies in which mode the file needs to be opened. Let’s look into the syntax of fopen() function and sample program that uses fopen() function.

Syntax:

fopen( $file, $mode );

Parameters:

  • $file specifies which file/URL to be open.
  • $mode indicates in which mode the specified $file needs to open like read, write modes.

It returns a file pointer on success or a Boolean value FALSE on failure.

PHP




<?php
  
// Opening a file in read mode
$myFile = fopen("Geeks_for_Geeks.txt", "r"
      or die("No such file/directory is present");
  
?>


Output:

No such file/directory is present

fclose() function: The fclose() function helps to close the opened files. The fclose() function accepts only one parameter $file and closes the file which is pointed by the $file. Let’s look into the syntax and sample program of fclose() function.

Syntax:

fclose($file)

Parameters:

  • $file is a pointer that points to the opened file.

It returns TRUE on success or FALSE on error.

PHP




<?php
  
// Opening a file in read mode
$myFile = fopen("Geeks_for_Geeks.txt", "r");
  
// Close the file using fclose()
fclose($myFile);
  
?>


Output:

True

Differences between fopen() and fclose() functions:

 

fopen()

fclose()

1

The fopen() function is used to open the file or an URL.

The fclose() function closes the opened file.

2

It accepts four parameters. ($file, $mode, $include_path, $context)

It accepts only 1 parameter. ($file)

3

$file, $mode are mandatory parameters among four. 

$file is the mandatory parameter.

4

It returns a file pointer on success or a Boolean value FALSE on failure.

It returns Boolean values only i.e. either TRUE or FALSE.

5

Syntax of fopen() function is-

fopen($file, $mode);

Syntax of fclose() function is-

fclose($file); 
RELATED ARTICLES

Most Popular

Dominic
32456 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6911 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS