Using PHP rewind() Function to Reset the File Pointer

This article explains PHP's rewind() function, detailing its syntax, parameters, return values, and providing two practical code examples that demonstrate resetting a file pointer for both reading and writing operations within a.

php Courses
php Courses
php Courses
Using PHP rewind() Function to Reset the File Pointer

PHP provides a rich set of functions for file manipulation, and one of them is rewind(). The rewind() function repositions the file pointer to the beginning of the file, allowing the file to be read again or other operations to be performed.

Usage:

rewind(resource $handle): bool

Parameter Description:

$handle : required. The file pointer resource.

Return Value:

Returns true on success, false on failure.

Example 1: Read file content and use rewind() to reset the pointer

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

// Read file content
while (!feof($file)) {
    echo fgets($file) . "<br>";
}

// Reset pointer to the beginning
rewind($file);

// Read file content again
while (!feof($file)) {
    echo fgets($file) . "<br>";
}

fclose($file);

The code opens example.txt, reads and outputs its content, calls rewind() to move the pointer back to the start, and reads the content a second time.

Example 2: Use rewind() during file write operations

$file = fopen("example.txt", "w+");

// Write to the file
fwrite($file, "Hello, PHP!");

// Reset pointer to the beginning
rewind($file);

// Read the written content
echo fgets($file);

fclose($file);

This example creates a new file with mode w+, writes a string, rewinds the pointer, and then reads back the written content.

Summary:

By using the rewind() function, developers can easily reposition the file pointer to the start of a file, enabling repeated reads or further processing after writing. Ensure the file is opened before calling rewind(), and combine it with other file‑handling functions as needed.

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.

BackendPHPfile-handlingfile-pointerrewind
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.