0
0
PHPprogramming~5 mins

File pointer manipulation in PHP

Choose your learning style9 modes available
Introduction

File pointer manipulation helps you move around inside a file. This lets you read or write at different places without starting over.

You want to skip the first few lines of a file and read from the middle.
You need to update a specific part of a file without rewriting the whole file.
You want to check the current position in a file while reading or writing.
You want to go back and re-read or overwrite some data in a file.
You want to jump to the end of a file to add more content.
Syntax
PHP
<?php
// Move file pointer
fseek(resource $handle, int $offset, int $whence = SEEK_SET): int

// Get current position
ftell(resource $handle): int

// Rewind pointer to start
rewind(resource $handle): void
?>

fseek moves the pointer to a new position.

ftell tells you where the pointer is now.

rewind moves pointer back to the start.

Examples
Move pointer 10 bytes from the start of the file.
PHP
<?php
$fp = fopen('file.txt', 'r');
fseek($fp, 10); // Move pointer 10 bytes from start
fclose($fp);
Move pointer 5 bytes before the end of the file.
PHP
<?php
$fp = fopen('file.txt', 'r');
fseek($fp, -5, SEEK_END); // Move pointer 5 bytes before end
fclose($fp);
Get the current position of the pointer.
PHP
<?php
$fp = fopen('file.txt', 'r');
$pos = ftell($fp); // Get current pointer position
fclose($fp);
Reset pointer to the beginning of the file.
PHP
<?php
$fp = fopen('file.txt', 'r');
rewind($fp); // Move pointer back to start
fclose($fp);
Sample Program

This program writes 'Hello World!' to a file, then moves the pointer to the word 'World' and overwrites it with 'PHP'. Finally, it reads and prints the updated content.

PHP
<?php
// Open file for reading and writing
$fp = fopen('example.txt', 'w+');

// Write some text
fwrite($fp, "Hello World!");

// Move pointer to 6th byte (start of 'World')
fseek($fp, 6);

// Overwrite 'World' with 'PHP'
fwrite($fp, "PHP");

// Move pointer back to start
rewind($fp);

// Read the whole content
$content = fread($fp, filesize('example.txt'));

// Close file
fclose($fp);

// Show result
print($content);
OutputSuccess
Important Notes

Remember to open the file with the correct mode to allow reading and writing.

Using fseek with SEEK_SET moves pointer from the start, SEEK_CUR from current position, and SEEK_END from the end.

Always close files with fclose to save changes and free resources.

Summary

File pointer lets you jump to any place in a file to read or write.

Use fseek to move the pointer, ftell to check position, and rewind to go back to start.

This helps update files efficiently without reading or writing everything again.