PHP fopen() Modes πŸ“

beginner
9 min

PHP fopen() Modes πŸ“

Welcome to our PHP fopen() Modes tutorial! In this lesson, we'll delve into PHP's fopen() function, which allows you to open a file for reading, writing, or appending. Let's get started!

Understanding fopen() 🎯

The fopen() function in PHP opens a file and returns a file pointer that we can use to interact with the file. The syntax is as follows:

php
$file_handle = fopen(filename, mode)
  • filename: The name of the file you want to open.
  • mode: The mode determines how we can access the file.

File Modes πŸ“

PHP provides several modes for opening files. Let's explore some of them:

r - Read-only (Open for reading only)

php
$file_handle = fopen("example.txt", "r");

πŸ“ Note: If the file doesn't exist, fopen() will return FALSE.

w - Write-only (Open for writing only. Overwrite existing file)

php
$file_handle = fopen("example.txt", "w");

πŸ“ Note: If the file exists, it will be overwritten. If it doesn't exist, a new file will be created.

a - Append (Open for appending. Create new file if it doesn't exist)

php
$file_handle = fopen("example.txt", "a");

πŸ“ Note: If the file doesn't exist, a new file will be created. If it does exist, the cursor will be placed at the end of the file.

x - Write-only (Create new file. Fail if file exists)

php
$file_handle = fopen("example.txt", "x");

πŸ“ Note: If the file exists, fopen() will return FALSE.

Advanced Examples 🎯

Writing to a file

php
$file_handle = fopen("example.txt", "w"); fwrite($file_handle, "Hello, World!"); fclose($file_handle);

Reading from a file

php
$file_handle = fopen("example.txt", "r"); $content = fread($file_handle, filesize("example.txt")); echo $content; fclose($file_handle);

Quiz 🎯

Quick Quiz
Question 1 of 1

Which mode should you use to write to a file, overwriting the existing content?

Quick Quiz
Question 1 of 1

Which mode should you use to append content to a file?