In this fifth part of an eight-part series on working with file and operating systems with PHP, you'll learn how to read data from a file and move the file pointer. This article is excerpted from chapter 10 of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).
It's often useful to jump around within a file, reading from and writing to various locations. Several PHP functions are available for doing just this.
int fseek (resource handle, int offset [, int whence])
The fseek() function moves the handle's pointer to the location specified by offset. If the optional parameter whence is omitted, the position is set offset bytes from the beginning of the file. Otherwise, whence can be set to one of three possible values, which affect the pointer's position:
SEEK_CUR: Sets the pointer position to the current position plus offset bytes.
SEEK_END: Sets the pointer position to the EOF plus offset bytes. In this case, offset must be set to a negative value.
SEEK_SET: Sets the pointer position to offset bytes. This has the same effect as omitting whence.
int ftell (resource handle)
The ftell() function retrieves the current position of the file pointer's offset within the resource specified by handle.
int rewind (resource handle)
The rewind() function moves the file pointer back to the beginning of the resource specified by handle.
Please check back for the continuation of this article.