Using fopen() in PHP: Syntax, Parameters, and Practical Examples

This article explains PHP's fopen() function, detailing its syntax, parameters, and four practical code examples for reading, writing, appending, and accessing URLs, while emphasizing proper mode selection and the importance of closing file handles to release resources.

php Courses
php Courses
php Courses
Using fopen() in PHP: Syntax, Parameters, and Practical Examples

In PHP, the fopen() function opens a file or URL for reading or writing, and is widely used for file I/O operations.

Syntax:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

Parameters:

$filename : required, the file or URL to open.

$mode : required, specifies the opening mode such as "r" (read), "w" (write), "a" (append), "x" (create), and optional "b" for binary.

$use_include_path : optional boolean, whether to search the include_path.

$context : optional, stream context resource for additional options.

Below are several practical examples demonstrating common uses of fopen():

Example 1: Reading a file

<?php
$filename = "example.txt";
$file = fopen($filename, "r");

if ($file) {
    while (!feof($file)) {
        echo fgets($file);
    }
    fclose($file);
} else {
    echo "Unable to open file!";
}
?>

Example 2: Writing to a file

<?php
$filename = "example.txt";
$file = fopen($filename, "w");

if ($file) {
    fwrite($file, "Hello, World!");
    fclose($file);
} else {
    echo "Unable to open file!";
}
?>

Example 3: Appending to a file

<?php
$filename = "example.txt";
$file = fopen($filename, "a");

if ($file) {
    fwrite($file, "Hello, PHP!");
    fclose($file);
} else {
    echo "Unable to open file!";
}
?>

Example 4: Opening a URL

<?php
$url = "http://www.example.com";
$file = fopen($url, "r");

if ($file) {
    while (!feof($file)) {
        echo fgets($file);
    }
    fclose($file);
} else {
    echo "Unable to open URL!";
}
?>

Summary

The fopen() function is a versatile PHP tool for opening files or URLs to read or write data; ensure correct permissions and mode, and always close the handle after operations to free resources.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPCode ExamplesTutorialfile-handlingfopen
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.