Home >Backend Development >PHP Tutorial >fopen() function in PHP

fopen() function in PHP

PHPz
PHPzforward
2023-08-27 21:41:062210browse

fopen() function in PHP

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

Syntax

fopen(file_path, mode, include_path, context)

Parameters

  • file_path − The path to 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. Open and write to the end of the file, or create a new file if it does not exist)
    • "a " - read/write. Preserve file contents by writing to end of file)
    • "x" - write only. Create new file. Returns FALSE and an error if the file already exists)
    • "x " - read/write. Create new file. Returns FALSE and error if the file already exists)
  • incude_path − If you want to search for a file in include_path (in php.ini), Please set it to '1'.

  • context − The context of the file pointer.

Return value

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

Suppose we have a file named "new.txt" with the following content.

The content of the file!

Now, let’s see an example -

Example

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

Output

The content of the file!

Let’s see an example of a “one.txt” file.

Example

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

Output

demo content

The above is the detailed content of fopen() function in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete