fopen() function in PHP


The fopen() function opens a file or URL. If the function fails, it returns FALSE and an error on failure. Add an '@' in front of the function name to hide the error output.

Syntax

fopen(file_path, mode, include_path, context)

Parameters

  • file_path − The path of the file.

  • mode − The type of access you require to the file

    • “r” - Read Only
    • "r+" - Read/Write
    • "w" - Write only
    • "w+" - Read/Write
    • "a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
    • "a+" - Read/Write. Preserves file content by writing to the end of the file)
    • "x" - Write only. Creates a new file. Returns FALSE and an error if file already exists)
    • "x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists)
  • incude_path − Set it to '1' if you want to search for the file in the include_path (in php.ini) as well.

  • context − the context of the file pointer.

Return

The fopen() function returns returns FALSE and an error on failure. Add an '@' in front of the function name to hide the error output.

Let’s say we have a file “new.txt” with the following content.

The content of the file!

Now, let us see the example −

Example

<?php
   // read/ write mode
   $file_pointer = fopen("new.txt", 'r+')
   or die("File does not exist");
   $res = fgets($file_pointer);
   echo $res;
   fclose($ile_pointer);
?>

Output

The content of the file!

Let us see an example with “one.txt” file.

Example

<?php
   // read/write mode
   $file_pointer = fopen("one.txt", "w+");
   // writing to file
   fwrite($file_pointer, 'demo content');
   echo fread($file_pointer, filesize("new.txt"));
   fclose($file_pointer);
?>

Output

demo content

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements