USING PHP TO MANAGE FILES To move the (Web host server)
Friday, January 25th, 2008USING PHP TO MANAGE FILES To move the pointer to the beginning of a file Pass the reference to the open file to rewind() like this: rewind($file); To move the pointer to the end of a file This is a little more complex. You need to use fseek(), which moves the pointer to a location specified by an offset and a PHP constant. The constant that represents the end of the file is SEEK_END, so an offset of 0 bytes places the pointer where you want it. You also need to pass fseek() a reference to the open file, so all three arguments together look like this: fseek($file, 0, SEEK_END); SEEK_END is a constant, so it doesn t need quotes, and it must be in uppercase. This is probably the only way you ll need to use fseek(), but you can also use it to move the internal pointer to a specific position or relative to its current position. For details, see www.php.net/manual/en/function.fseek.php. The file fopen_pointer.php uses the fopen() r+ mode to demonstrate combining several read and write operations, and the effect of moving the pointer. The main code looks like this: $filename = ‘C:/private/filetest05.txt’; // open a file for reading and writing $file = fopen($filename, ‘r+’); // the pointer is at the beginning, so existing content is overwritten fwrite($file, $contents); // read the contents from the current position $readRest = ‘’; while (!feof($file)) { $readRest .= fgets($file); } // reset internal pointer to the beginning rewind($file); // read the contents from the beginning (nasty gotcha here) $readAll = fread($file, filesize($filename)); // pointer now at the end, so write the form contents again fwrite($file, $contents); // read immediately without moving the pointer $readAgain = ‘’; while (!feof($file)) { $readAgain .= fgets($file); } // close the file fclose($file); 193
In case you need quality webspace to host and run your web applications, try our personal web hosting services.