0
0
PHPprogramming~5 mins

File open modes in PHP

Choose your learning style9 modes available
Introduction

File open modes tell PHP how you want to use a file, like reading or writing. They help PHP know what to do with the file.

When you want to read data from a file, like reading a list of names.
When you want to write new data to a file, like saving user input.
When you want to add data to the end of an existing file without erasing it.
When you want to create a new file or overwrite an old one.
When you want to update parts of a file without deleting everything.
Syntax
PHP
$file = fopen('filename.txt', 'mode');

The mode is a string that tells PHP how to open the file.

Common modes include 'r' for read, 'w' for write, and 'a' for append.

Examples
Open data.txt for reading only.
PHP
$file = fopen('data.txt', 'r');
Open log.txt to add new data at the end.
PHP
$file = fopen('log.txt', 'a');
Open notes.txt for writing, erasing old content.
PHP
$file = fopen('notes.txt', 'w');
Open report.txt for reading and writing.
PHP
$file = fopen('report.txt', 'r+');
Sample Program

This program creates a file called example.txt, writes "Hello, world!" to it, then reads and prints the content.

PHP
<?php
$filename = 'example.txt';

// Open file for writing (this will create or erase the file)
$file = fopen($filename, 'w');

// Write a line to the file
fwrite($file, "Hello, world!\n");

// Close the file
fclose($file);

// Open file for reading
$file = fopen($filename, 'r');

// Read the content
$content = fread($file, filesize($filename));

// Close the file
fclose($file);

// Show the content
echo $content;
?>
OutputSuccess
Important Notes

Always close a file with fclose() to free system resources.

Using 'w' mode erases the file content if it exists, so be careful.

Use 'a' mode to add data without deleting existing content.

Summary

File open modes tell PHP how to access a file (read, write, append).

Choose the mode based on what you want to do with the file.

Always close files after opening them to avoid problems.