Backend Development 4 min read

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) . "
";
}

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

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

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.

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

login 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.