- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements