Difference between r+ and w+ in fopen()

Both r+ and w+ can read and write to a file. However, r+ doesn’t delete the content of the file and doesn’t create a new file if such file doesn’t exist, whereas w+ deletes the content of the file and creates it if it doesn’t exist.

How do I open a file from line X to line Y in PHP?

Yes, you can do that easily with SplFileObject::seek $file = new SplFileObject(‘filename.txt’); $file->seek(1000); for($i = 0; !$file->eof() && $i < 1000; $i++) { echo $file->current(); $file->next(); } This is a method from the SeekableIterator interface and not to be confused with fseek. And because SplFileObject is iterable you can do it even easier with a … Read more

How to read only 5 last line of the text file in PHP?

For a large file, reading all the lines into an array with file() is a bit wasteful. Here’s how you could read the file and maintain a buffer of the last 5 lines: $lines=array(); $fp = fopen(“file.txt”, “r”); while(!feof($fp)) { $line = fgets($fp, 4096); array_push($lines, $line); if (count($lines)>5) array_shift($lines); } fclose($fp); You could optimize this … Read more

PHP check if file contains a string

Much simpler: <?php if( strpos(file_get_contents(“./uuids.txt”),$_GET[‘id’]) !== false) { // do stuff } ?> In response to comments on memory usage: <?php if( exec(‘grep ‘.escapeshellarg($_GET[‘id’]).’ ./uuids.txt’)) { // do stuff } ?>

fopen deprecated warning

It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they’re providing aren’t portable. Anyway, if you aren’t interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example: #define _CRT_SECURE_NO_DEPRECATE … Read more

Reading from a frequently updated file

I would recommend looking at David Beazley’s Generator Tricks for Python, especially Part 5: Processing Infinite Data. It will handle the Python equivalent of a tail -f logfile command in real-time. # follow.py # # Follow a file like tail -f. import time def follow(thefile): thefile.seek(0,2) while True: line = thefile.readline() if not line: time.sleep(0.1) … Read more