fopen() in PHP

File handling is a very important concept in the world of computer science. Files are a type of portable storage used to store any type of data. Before a programmer applies any algorithm on a particular file, they need to open that file using the fopen() command.

Syntax

Only two parameters are passed into the fopen() function:

  • Name of the file
  • File permissions
$file = fopen("filename.txt", "r");

File permissions

  • r = Reads a file if it exists.
  • w = Writes in an existing file.
  • r+ = Reads a file for input and output; the file must exist.
  • w+ = Creates files and opens them for both input and output.

Code

The following code opens a file and writes “Educative!” in it.

<?php
$file = fopen("filename.txt", "w+");
$company = "Educative!\n";
fwrite($file, $company);
fclose($file);
?>

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved