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

fopen() function in PHP

PHPz
Release: 2023-08-27 21:42:02
forward
2177 people have browsed it

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)
Copy after login

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!
Copy after login
Copy after login

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);
?>
Copy after login

Output

The content of the file!
Copy after login
Copy after login

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);
?>
Copy after login

Output

demo content
Copy after login

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

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template